在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
当前回答
如果你使用gmap V3插件: $(" #地图”).gmap(“removeAllMarkers”);
参见:http://www.smashinglabs.pl/gmap/documentation #后载荷
其他回答
同样的问题。这段代码不再工作了。
我已经纠正了它,这样改变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
for (i in markersArray) {
markersArray[i].setMap(null);
}
只在IE上工作。
for (var i=0; i<markersArray.length; i++) {
markersArray[i].setMap(null);
}
工作在chrome, firefox,如…
我发现使用google-maps-utility-library-v3项目中的markermanager库是最简单的方法。
1. 设置标记管理器
mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function () {
loadMarkers();
});
2. 向MarkerManager添加标记
function loadMarkers() {
var marker = new google.maps.Marker({
title: title,
position: latlng,
icon: icon
});
mgr.addMarker(marker);
mgr.refresh();
}
3.要清除标记,只需要调用MarkerManger的clearMarkers()函数
mgr.clearMarkers();
在V3中似乎还没有这样的函数。
人们建议将对地图上所有标记的引用保存在一个数组中。然后当你想把它们全部删除时,只需要在数组中循环,并对每个引用调用. setmap (null)方法。
更多信息/代码请参见这个问题。
我的版本:
google.maps.Map.prototype.markers = new Array();
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();
};
google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;
google.maps.Marker.prototype.setMap = function(map) {
if (map) {
map.markers[map.markers.length] = this;
}
this._setMap(map);
}
该代码是此代码http://www.lootogo.com/googlemapsapi3/markerPlugin.html的编辑版本,我删除了手动调用addMarker的需要。
Pros
这样做可以使代码保持紧凑和在一个地方(不会污染名称空间)。 你不再需要自己跟踪标记你可以通过调用map。getmarkers()找到地图上的所有标记
Cons
Using prototypes and wrappers like I did now makes my code dependent on Google code, if they make a mayor change in their source this will break. If you don't understand it then you won't be able to fix it if does break. The chances are low that they're going to change anything which will break this, but still.. If you remove one marker manually, it's reference will still be in markers array. (You could edit my setMap method to fix it, but at the cost of looping trough markers array and removing the reference)
这是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.