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

map.clearOverlays();

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

看看参考API,我不清楚。


当前回答

要从地图中删除所有标记,创建如下函数:

1.addMarker(location):这个函数用于在地图上添加标记

2.clearMarkers():该函数从map中移除所有标记,而不是数组中

3.setMapOnAll(map):这个函数用于在数组中添加标记信息

4.deleteMarkers():该函数通过删除对数组中所有标记的引用来删除它们。

// Adds 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 setMapOnAll(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() {
    setMapOnAll(null);
  }

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

其他回答

最干净的方法是遍历地图的所有功能。标记(以及多边形、折线等)存储在地图的数据层中。

function removeAllMarkers() {
  map.data.forEach((feature) => {
    feature.getGeometry().getType() === 'Point' ? map.data.remove(feature) : null
  });
}

在通过绘图管理器添加标记的情况下,最好创建一个全局标记数组,或者在创建时将标记推入数据层,如下所示:

google.maps.event.addListener(drawingManager, 'overlaycomplete', (e) => {
    var newShape = e.overlay;
    newShape.type = e.type;

    if (newShape.type === 'marker') {
      var pos = newShape.getPosition()
      map.data.add({ geometry: new google.maps.Data.Point(pos) });

      // remove from drawing layer
      newShape.setMap(null);
    }
  });

我推荐第二种方法,因为它允许您稍后使用其他google.maps.data类方法。

如果你使用gmap V3插件: $(" #地图”).gmap(“removeAllMarkers”);

参见:http://www.smashinglabs.pl/gmap/documentation #后载荷

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

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

对我来说每次都管用。

清空Googlemap

mGoogle_map.clear();

这是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.