谷歌地图标记无法删除

3

我在使用Google地图web应用时遇到了标记问题。我可以添加标记,但无法删除它们。我已经寻找了几天的解决方案,但是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);

    }

}

placeMarker函数长什么样子? - geocodezip
你认为这个 window.myPositionMarker.setMap(null); 是指什么?我觉得应该是 window.markers[i].setMap(null);,其中 "i" 是你想要隐藏的特定标记的索引(对于你的原始示例来说,它将是 window.markers.length-1,即最后添加的标记)。 - geocodezip
谢谢,你说得对。虽然我不太明白为什么我不能将标记器引用为window.myPositionMarker(它已被声明为全局变量),但当我将其作为window.markers [0]引用时,它会像预期的那样被删除。感谢您的帮助 :) - user3535074
4个回答

2

我认为你问题的根本原因是你没有真正地处理你认为的对象,而是使用了 .setMap(null) 方法。

尝试从 placeMarker() 函数中返回你的标记,并将其赋值给一个变量,然后在该变量上调用 setMap(null) 方法。

如果你在初始化 google.maps.marker() 后声明 window.myPositionMarker = marker,它将按预期工作。


谢谢,你说得对。虽然我不太明白为什么我不能将标记器引用为window.myPositionMarker(它已被声明为全局变量),但当我将其作为window.markers [0]引用时,它会被删除,就像我预期的那样。感谢您的帮助 :) - user3535074

2

看起来你的问题已经得到解决,但是对于其他遇到此问题的人,需要提前警告 -

我在标记上设置自定义属性后,无法删除它们。

例如:

// can create a marker and add it to map OK
marker = new new google.maps.Marker({...})
marker.setMap(map)

// But don't set a custom property on the marker
marker.foo = "bar"
marker.setMap(null) // wont remove the marker

0
在我的情况下,我使用了谷歌的MarkerClusterer,并且有我们自己对标记对象的引用,这导致它无法被移除。
一旦我移除了我们自己的引用,标记将由Clusterer自身进行清理。

0

当创建一个新的标记时,它无法通过其全局名称myPositionMarker进行引用。然而,在创建标记的过程中,它被放置在一个数组中。如果我将标记称为

window.markers[0].setMap(null);

正如预期的那样,它已从地图中移除。非常感谢您的帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接