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 A
for (i in markersArray) {
markersArray[i].setMap(null);
}
is only working on IE.
for (var i=0; i<markersArray.length; i++) {
markersArray[i].setMap(null);
}
working on chrome, firefox, ie...
You can do it this way too:
function clearMarkers(category){
var i;
for (i = 0; i < markers.length; i++) {
markers[i].setVisible(false);
}
}
The cleanest way of doing this is to iterate over all the features of the map. Markers (along with polygons, polylines, ect.) are stored in the data layer of the map.
function removeAllMarkers() {
map.data.forEach((feature) => {
feature.getGeometry().getType() === 'Point' ? map.data.remove(feature) : null
});
}
In the case that the markers are being added via drawing manager, it's best to create a global array of markers or pushing the markers into the data layer on creation like so:
google.maps.event.addListener(drawingManager, 'overlaycomplete', (e) => {
var newShape = e.overlay;
newShape.type = e.type;
if (newShape.type === 'marker') {
var pos = newShape.getPosition()
map.data.add({ geometry: new google.maps.Data.Point(pos) });
// remove from drawing layer
newShape.setMap(null);
}
});
I recommend the second approach as it allows you to use other google.maps.data class methods later.
just clear Googlemap
mGoogle_map.clear();
The following from Anon works perfectly, although with flickers when repeatedly clearing the overlays.
Simply do the following:
I. Declare a global variable:
var markersArray = [];
II. Define a function:
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
III. Push markers in the 'markerArray' before calling the following:
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});
IV. Call the clearOverlays()
function wherever required.
That's it!!
Hope that will help you.
if you use the gmap V3 plugin:
$("#map").gmap("removeAllMarkers");
see: http://www.smashinglabs.pl/gmap/documentation#after-load