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

map.clearOverlays();

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

看看参考API,我不清楚。


当前回答

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

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

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

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

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

“Delete”也会清除数组。

其他回答

你也可以这样做:

function clearMarkers(category){ 
  var i;       

  for (i = 0; i < markers.length; i++) {                          
    markers[i].setVisible(false);        
  }    
}

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

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

对我来说每次都管用。

在新版本v3上,他们建议保持在数组中。如下。

参见overlay-overview中的示例。

var map;
var markersArray = [];

function initialize() {
  var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
  var mapOptions = {
    zoom: 12,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng);
  });
}

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

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

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 = [];
}
for (i in markersArray) {
  markersArray[i].setMap(null);
}

只在IE上工作。


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

工作在chrome, firefox,如…