我在 Google map 网络应用程序中遇到标记问题。我可以添加标记,但无法删除它们。我一直在寻找解决方案几天,但 v3 的标准建议似乎是:
marker.setMap(null);
问题是这在我的代码中似乎完全无效。这是在启动时运行的函数示例。它以低精度快速获取当前位置。需要更长时间才能完成的后续功能应删除标记并将新标记放置在更准确的位置。问题是,一旦放置,我就无法移除标记。
function geoLocCheckAndFastLatLng(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//get current position
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
//place low accuracy marker
placeMarker(pos,window.meIconMediumAccuracy,window.myPositionMarker);
//and center map
window.map.setCenter(pos);
window.map.setZoom(14);
window.myPositionMarker.setMap(null);
});
}else{
alert("Sorry - You're Browser Doesn't Support Geolocation.\nChange To Google-Chrome Or Dolphin To Use This App");
}
}
因此,上述函数在理论上获取了位置,放置了一个标记,然后删除了相同的标记。但是标记仍然存在!有人可以帮忙吗?我只有几天的时间才能完成,但我不明白哪里出了问题。
这是位置标记函数:
function placeMarker(location, iconType, marker) {
//alert(window.markers.length);
//if the marker is undefined it means it needs to be created form scratch
//using the iconType and location provided in the function call
if(marker === undefined){
marker = new google.maps.Marker(
{
position: location,
map: window.map,
icon: iconType,
});
//and add a click listener
google.maps.event.addListener(marker, 'click', function()
{
alert("Marker location:\n" + pos);
});
//add to markers array
window.markers.push(marker);
}else{
marker.setPosition(location);
}
}
最佳答案
我认为您的问题的根本原因是您实际上并没有通过 .setMap(null) 调用来处理您认为自己所在的对象。
尝试从 placeMarker() 返回您的标记,然后将其分配给一个 var 并在其上调用 setMap(null)。
如果您在初始化 google.maps.marker() 后声明 window.myPositionMarker = marker,它将按预期工作。
关于javascript - 无法删除 Google map 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24253092/