我有一个脚本,我可以在谷歌地图中应用搜索半径。我可以更改半径并使其动态显示,但似乎无法弄清楚如何替换半径而不仅仅是添加半径。该函数使用 bindTo 标记。我尝试了替换和替换,但它们似乎不起作用。
这是范围输入 -
<input type="range" class="custom-range" id="customRange1" value="20">
这是添加标记脚本,创建半径并在范围值更改时绑定它。
var marker = new google.maps.Marker({
map: map,
position: latLng,
title: name,
icon: 'linktoimage'
});
// Add circle overlay and bind to marker
$('#customRange1').change(function(){
var new_rad = $(this).val();
var rad = new_rad * 1609.34;
var circle = new google.maps.Circle({
map: map,
radius:rad,
fillColor: '#555',
strokeColor: '#ffffff',
strokeOpacity: 0.1,
strokeWeight: 3
});
circle.bindTo('center', marker, 'position');
});
因此,当我更改范围值时,它将在旧覆盖层之上添加新的半径叠加层,我希望它用新的半径叠加层替换当前的半径叠加层。我猜是因为我正在使用绑定。
保留对圆的引用,如果圆已经存在,请不要创建一个新的圆圈,更改现有的圆圈:
var circle;
// Add circle overlay and bind to marker
$('#customRange1').change(function() {
var new_rad = $(this).val();
var rad = new_rad * 1609.34;
if (!circle || !circle.setRadius) {
circle = new google.maps.Circle({
map: map,
radius: rad,
fillColor: '#555',
strokeColor: '#ffffff',
strokeOpacity: 0.1,
strokeWeight: 3
});
circle.bindTo('center', marker, 'position');
} else circle.setRadius(rad);
});
概念验证小提琴
代码片段:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
var circle;
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
title: "name"
});
// Add circle overlay and bind to marker
$('#customRange1').change(function() {
var new_rad = $(this).val();
var rad = new_rad * 1609.34;
if (!circle || !circle.setRadius) {
circle = new google.maps.Circle({
map: map,
radius: rad,
fillColor: '#555',
strokeColor: '#ffffff',
strokeOpacity: 0.1,
strokeWeight: 3
});
circle.bindTo('center', marker, 'position');
} else circle.setRadius(rad);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" class="custom-range" id="customRange1" value="20">
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>