在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
当前回答
在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)
其他回答
我不知道为什么,但是,设置setMap(null)到我的标记并不适用于我,当我使用DirectionsRenderer。
在我的情况下,我必须调用setMap(null)到我的DirectionsRenderer以及。
就像这样:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
if (map.directionsDisplay) {
map.directionsDisplay.setMap(null);
}
map.directionsDisplay = directionsDisplay;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
我尝试了所有提出的解决方案,但当我所有的标记都在一个集群下时,没有一个对我有效。 最后我写了这个:
var markerCluster = new MarkerClusterer(map, markers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
agentsGpsData[agentGpsData.ID].CLUSTER = markerCluster;
//this did the trick
agentsGpsData[agentId].CLUSTER.clearMarkers();
换句话说,如果你在一个集群中包装标记,并想要删除所有标记,你调用:
clearMarkers();
你是说删除是指隐藏它们还是删除它们?
如果隐藏:
function clearMarkers() {
setAllMap(null);
}
如果你想删除它们:
function deleteMarkers() {
clearMarkers();
markers = [];
}
注意,我使用数组标记来跟踪它们,并手动重置它。
如果你使用gmap V3插件: $(" #地图”).gmap(“removeAllMarkers”);
参见:http://www.smashinglabs.pl/gmap/documentation #后载荷
我使用的速记法很好地完成了这项工作。只做
map.clear();