在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:

map.clearOverlays();

我如何做到这一点在谷歌地图API v3?

看看参考API,我不清楚。


当前回答

您需要将map null设置为该标记。

var markersList = [];    

function removeMarkers(markersList) {
   for(var i = 0; i < markersList.length; i++) {
      markersList[i].setMap(null);
   }
}

function addMarkers() {
   var marker = new google.maps.Marker({
        position : {
            lat : 12.374,
            lng : -11.55
        },
        map : map
       });
      markersList.push(marker);
   }

其他回答

谷歌的Demo Gallery有一个关于他们如何做到这一点的演示:

http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html

您可以查看源代码以查看它们如何添加标记。

长话短说,他们把标记保存在一个全局数组中。当清除/删除它们时,它们循环遍历数组,并在给定的标记对象上调用". setmap (null)"。

然而,这个例子展示了一个“技巧”。对于本例,“清除”意味着将它们从映射中删除,但将它们保留在数组中,这允许应用程序快速将它们重新添加到映射中。在某种意义上,这就像“隐藏”它们。

“Delete”也会清除数组。

我知道这可能是一个简单的解决方案,但这就是我所做的

$("#map_canvas").html("");
markers = [];

对我来说每次都管用。

我找到了一个简单的解决方法(我认为):

var marker = new google.maps.Marker();

function Clear(){
     marker.setMap(null);
}

这是YingYang于2014年3月11日15:049在对用户原始问题的原始回复下发布的所有解决方案中最简单的一个

2.5年后,我在谷歌地图v3.18中使用了他的相同解决方案,它就像一个魅力

markersArray.push(newMarker) ;
while(markersArray.length) { markersArray.pop().setMap(null); }

// No need to clear the array after that.

在这里你可以找到一个如何删除标记的例子:

https://developers.google.com/maps/documentation/javascript/examples/marker-remove?hl=es

// Add a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
   }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}