Google Maps API v3: How to remove all markers?
In Google Maps API v2, if I wanted to remove all the map markers, I could simply do:
map.clearOverlays();
How do I do this in Google Maps API v3 ?
Looking at the Reference API, it's unclear to me.
Simply do the following:
I. Declare a global variable:
var markersArray = [];
II. Define a function:
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
OR
google.maps.Map.prototype.clearOverlays = function() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
III. Push markers in the 'markerArray' before calling the following:
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});
IV. Call the clearOverlays();
or map.clearOverlays();
function wherever required.
That's it!!
Same problem. This code doesn't work anymore.
I've corrected it, change clearMarkers method this way:
set_map(null) ---> setMap(null)
google.maps.Map.prototype.clearMarkers = function() {
for(var i=0; i < this.markers.length; i++){
this.markers[i].setMap(null);
}
this.markers = new Array();
};
Documentation has been updated to include details on the topic: https://developers.google.com/maps/documentation/javascript/markers#remove
It seems that there is no such function in V3 yet.
People suggest to keep references to all markers you have on the map in an array. And then when you want to delete em all, just loop trough the array and call .setMap(null) method on each of the references.
See this question for more info/code.
My version:
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);
}
The code is edited version of this code http://www.lootogo.com/googlemapsapi3/markerPlugin.html I removed the need to call addMarker manually.
Pros
Cons