我正在编写一个 Web 应用程序,该应用程序在 Google map 上的一个标记周围显示一个圆圈。 placeMarker(location, radius)
在 location
设置一个标记,并将其绑定(bind)到一个具有半径的圆。我希望脚本在每次调用 placeMarker 时重新绘制圆和标记。当我在控制台中尝试它时,它会使用新位置重新绘制标记,但保留原始圆半径。 undefined
也会被打印出来。我需要更改什么才能使其正常工作?
var map;
var marker;
function placeMarker(location, radius) {
if (typeof radius === 'undefined') { radius = initialRadius; }
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
}
var circle = new google.maps.Circle({
map: map,
radius: radius,
fillColor: '#AA0000',
});
circle.bindTo('center', marker, 'position');
}
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 1
});
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
google.maps.event.addDomListener(window, "resize", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
}
最佳答案
您需要执行与标记类似的操作。也就是说,不是创建一个新的circle
对象并将其绑定(bind)到 map 。您需要使用 circle.setCenter(latlng)
API 重新定位现有圆。
参见:
https://developers.google.com/maps/documentation/javascript/reference#Circle
不幸的是,您这里没有 JSFiddle 设置,否则我可以尝试为您修复它。但是您的代码应该如下所示。
var map;
var marker;
var myCircle;
function placeMarker(location, radius) {
if (typeof radius === 'undefined') { radius = initialRadius; }
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
}
if (myCircle) {
// Don't create new circle, update circle position instead.
myCircle.setCenter(location); // where location=latLng
}
else {
// First time loading, create the circle
myCircle = new google.maps.Circle({
map: map,
radius: radius,
fillColor: '#AA0000',
});
myCircle.bindTo('center', marker, 'position');
}
}
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 1
});
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
google.maps.event.addDomListener(window, "resize", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
}
关于javascript - 在函数调用时重绘 Google map 圆圈和标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38492867/