Google Maps API v3: How to remove all markers?

528,131

Solution 1

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

Solution 2

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

  • Doing this way you keep the code compact and in one place (doesn't pollute the namespace).
  • You don't have to keep track of the markers yourself anymore you can always find all the markers on the map by calling 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)

Solution 3

This was the most simple of all the solutions originally posted by YingYang Mar 11 '14 at 15:049 under the original response to the users original question

I am using his same solution 2.5 years later with google maps v3.18 and it works like a charm

markersArray.push(newMarker) ;
while(markersArray.length) { markersArray.pop().setMap(null); }

// No need to clear the array after that.

Solution 4

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();
};

I don't think there is one in V3 so I used the above custom implementation.

Disclaimer: I did not write this code but I forgot to retain a reference when I merged it into my codebase so I don't know where it came from.

Solution 5

On the new version v3, They recommended to keep in arrays. as following.

See sample at overlay-overview.

var map;
var markersArray = [];

function initialize() {
  var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
  var mapOptions = {
    zoom: 12,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng);
  });
}

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}
Share:
528,131
mp_
Author by

mp_

Updated on October 13, 2020

Comments

  • mp_
    mp_ over 3 years

    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.

  • Maiku Mori
    Maiku Mori over 14 years
    +1 From me. I'd add a wrapper around google.maps.Marker constructor (or setMap method since I think the constructor calls it internally) which calls addMarker automatically, but still nice answer :).
  • Andrew
    Andrew over 14 years
    +1 From me. But your answer would be better if you included the wrapper to call addMarker automatically!
  • mp_
    mp_ over 14 years
    @Maiku Mari, would you show with code what you'd do different and why. Thanks
  • mp_
    mp_ over 14 years
    I assume you're referring to Andrews answer actually. Would you show with code what you'd do different and why. Thanks
  • Maiku Mori
    Maiku Mori over 14 years
    Meh sorry for delay, I was holding back from posting code because I had no way to quickly test it.
  • mp_
    mp_ over 14 years
    Thanks Maiku. Though, I don't understand - how do I add a new marker in your example. Again, many many thanks!
  • Petrogad
    Petrogad over 14 years
    How is this not the solution? You remove markers by using set_map(null) on the particular marker you want to clear, if you want to clear all then loop through using this function. If you want something more request it here: code.google.com/p/gmaps-api-issues/issues/…
  • Maiku Mori
    Maiku Mori over 14 years
    I believe it came from here lootogo.com/googlemapsapi3/markerPlugin.html
  • Sebastian
    Sebastian about 14 years
    The way I finally got it working was to iterate through the markers collection where I stored them and use setMap(null)
  • Tomas
    Tomas about 14 years
    -1 Bad style. There is only one markers array created, but one per map after clearMarkers (cause of get/set difference with prototypes). Nasty bugs with multiple map objects.
  • Nick
    Nick almost 14 years
    But does this clear the markers from memory? I realize JavaScript has automatic garbage collection, but how do we know Google's API does not hold a reference to the marker when setMap(null) is called? In my application, I add and "delete" a ton of markers, and I would hate for all those "deleted" markers to be sucking up memory.
  • DaveS
    DaveS over 13 years
    @Nick: add 'delete this.markers[i];' after the setMap(null) bit.
  • lashleigh
    lashleigh over 13 years
    This question is answered in the documentation now. code.google.com/apis/maps/documentation/javascript/…
  • InterfaceGuy
    InterfaceGuy almost 12 years
    I tried using setMap(null), but I had an auto-updating script, and every time I set all 50 or so of my markers to a null map, I still had a bunch of mapless markers floating around in the DOM somewhere. This kept causing the page to crash because each 30 seconds it added 50 new markers to the DOM, and this propagated endlessly because the page stayed open 24/7 on a video wall. I had to use the top answer and clear all map overlays from the DOM entirely before creating new ones. Hope this helps someone; it took a long time for me to figure out why my page was crashing! :(
  • codeimplementer
    codeimplementer over 11 years
    It seems like quite a lot of overkill to pull that library in for clearing the markers. All clearMarkers do is iterate over the markers calling marker.setMap(null) (i checked the source). It would be less work putting them in an array and doing it yourself.
  • codeimplementer
    codeimplementer over 11 years
    for(in in markersArray){} probably doesn't do what you expect it to do. If Array is extended anywhere else in the code it'll iterate over those properties as well, and not just the indexes. The javascript version of that is markersArray.forEach() which isn't supported everywhere. You'd be better of with for(var i=0; i<markersArray.length; ++i){ markersArray.setMap(null); }
  • Rihards
    Rihards over 11 years
    Who even uses new Array(); ?
  • freefaller
    freefaller over 11 years
    Please read the help regarding the formatting of code on SO
  • Kichu
    Kichu over 10 years
    wouldn't this also reset the map ? suppose if the user had dragged the map to a new area ?
  • Someone
    Someone over 8 years
    $("#map_canvas").html(""); would in fact wipe the entire map div clean and also relies on jQuery so your response is both stupid and unhelpful.
  • kronus
    kronus over 8 years
    Yes, that is correct. Initialize the map and the markers
  • Someone
    Someone over 8 years
    But he doesn't want to reinitialize the map he wants to remove existing markers....
  • kronus
    kronus over 8 years
    I am just offering the way that I have found to remove existing markers. At least give it a shot and tell me if it worked or not. It works for me
  • Someone
    Someone over 8 years
    Tried it just now out of interest and as suspected makes the map go grey and removes all content
  • kronus
    kronus over 8 years
    Yes, then you re-init the map, followed by the new markers. It will occur so fast, that the end user will not see the grey
  • Someone
    Someone over 8 years
    The whole point of wanting to remove map markers is to avoid having to reinitialize the map, situations like mine meant that because I was using googles drawing library for drawing on the map if I clear it off and reinitialize the whole map all the overlays I drew disappear the only way to stop that is to store all the overlays and re add them which is also a lot of unnecessary work. Reinitialize the map is not removing the markers its recreating it from scratch again NOT removing the markers.
  • lalithkumar
    lalithkumar almost 7 years
    Is this differ from RejoylinLokeshwaran's answer?