我正在编写一个web应用程序,它在谷歌地图上显示一个圆圈围绕一个标记。placeMarker(location, radius)
在location
处设置一个Marker,并将一个半径为的Circle绑定到该Marker。我希望每次调用placeMarker时脚本都重新绘制Circle和Marker。当我在控制台中尝试它时,它会用新位置重新绘制标记,但保留原始圆半径。还打印CCD_ 3。我需要更改什么才能使其工作?
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
对象并将其绑定到映射。您需要使用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);
});
}