在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
当前回答
同样的问题。这段代码不再工作了。
我已经纠正了它,这样改变clearMarkers方法:
set_map(空) ---> setMap(空)
google.maps.Map.prototype.clearMarkers = function() {
for(var i=0; i < this.markers.length; i++){
this.markers[i].setMap(null);
}
this.markers = new Array();
};
文档已更新,包括关于主题的详细信息:https://developers.google.com/maps/documentation/javascript/markers#remove
其他回答
在两个答案中发布的“set_map”函数似乎不再在谷歌Maps v3 API中工作。
我想知道发生了什么事
更新:
似乎谷歌改变了他们的API,使“set_map”不是“setMap”。
http://code.google.com/apis/maps/documentation/v3/reference.html
google.maps.Map.prototype.markers = new Array();
google.maps.Map.prototype.addMarker = function(marker) {
this.markers[this.markers.length] = marker;
};
google.maps.Map.prototype.getMarkers = function() {
return this.markers
};
google.maps.Map.prototype.clearMarkers = function() {
for(var i=0; i<this.markers.length; i++){
this.markers[i].setMap(null);
}
this.markers = new Array();
};
我认为V3中没有,所以我使用了上面的自定义实现。
免责声明:我没有写这段代码,但我忘记保留引用时,我合并到我的代码库,所以我不知道它来自哪里。
使用这个你可以删除地图上的所有标记。
map.clear();
这对你有帮助,对我也有帮助。
这是谷歌自己在至少一个样本中使用的方法:
var markers = [];
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
检查谷歌样本完整的代码示例:
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
在这里你可以找到一个如何删除标记的例子:
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 = [];
}