436
votes

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.

30
I found some code at the link below, but holy cow - is that a lot of code to simulate the previous 1 line of code in v2 of the API. lootogo.com/googlemapsapi3/markerPlugin.htmlmp_
remember that maps 3.0 is meant to be VERY light in order for mobile devices to use it with as little lag as possible...Petrogad
The solutions suggested here appear to be broken as of 2010/07/29. I wish I had a working version to suggest instead.Jonathan Hanson
The highest rated answer is wrong. View source on this example to see how to do it: google-developers.appspot.com/maps/documentation/javascript/…Seb Ashton

30 Answers

491
votes

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!!

84
votes

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

47
votes

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)
25
votes

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.
21
votes
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.

18
votes

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;
  }
}
6
votes

Google's Demo Gallery has a demo on how they do it:

http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html

You can view the source code to see how they add markers.

Long story short, they keep the markers in a global array. When clearing/deleting them, they loop through the array and call ".setMap(null)" on the given marker object.

However, this example shows one 'trick'. "Clear" for this example means removing them from the map but keeping them in the array, which allows the application to quickly re-add them to the map. In a sense, this acts like "hiding" them.

"Delete" clears the array as well.

6
votes
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...

6
votes

A clean and easy application of rolinger's answer.

function placeMarkerAndPanTo(latLng, map) {
      while(markersArray.length) { markersArray.pop().setMap(null); }
      var marker = new google.maps.Marker({
        position: latLng,
        map: map
      });
      map.panTo(latLng);

      markersArray.push(marker) ;
    }
6
votes

The solution is quite easy. You may use the method: marker.setMap(map);. Here, you define on which map the pin will appear.

So, if you set null in this method (marker.setMap(null);), the pin will disappear.


Now, you can write a function witch while make disappear all markers in your map.

You just add to put your pins in an array and declare them with markers.push (your_new pin) or this code for example:

// Adds a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

This is a function witch can set or disappear all the markers of your array in the map:

// Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

To disappear all your markers, you should call the function with null:

// Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

And, to remove and disappear, all your markers, you should reset your array of markers like this:

// Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

This is my complete code. It’s the simplest I could reduce to. Be care full you may replace YOUR_API_KEY in the code by your key google API:

<!DOCTYPE html>
<html>
  <head>
  <title>Remove Markers</title>
  <style>
     /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
     #map {
       height: 100%;
       }
  </style>
</head>
<body>

<div id="map"></div>
<p>Click on the map to add markers.</p>
<script>

  // In the following example, markers appear when the user clicks on the map.
  // The markers are stored in an array.
  // The user can then click an option to hide, show or delete the markers.
  var map;
  var markers = [];

  function initMap() {
    var haightAshbury = {lat: 37.769, lng: -122.446};

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: haightAshbury,
      mapTypeId: 'terrain'
    });

    // This event listener will call addMarker() when the map is clicked.
    map.addListener('click', function(event) {
      addMarker(event.latLng);
    });

    // Adds a marker at the center of the map.
    addMarker(haightAshbury);
  }

   // Adds a marker to the map and push to the array.
  function addMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markers.push(marker);
  }

  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

  // Shows any markers currently in the array.
  function showMarkers() {
    setMapOnAll(map);
  }

  // Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

</script>
   <script async defer
    src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap">
   </script>
</body>
</html>

You may consult google developer or the complete documentation on, also, google developer web site.

4
votes

The "set_map" function posted in both answers appears to no longer work in Google Maps v3 API.

I wonder what happened

Update:

It appears Google changed their API such that "set_map" is not "setMap".

http://code.google.com/apis/maps/documentation/v3/reference.html

4
votes

Here you can find an example of how to remove markers:

https://developers.google.com/maps/documentation/javascript/examples/marker-remove?hl=es

// Add a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
   }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}
3
votes

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.

3
votes

I found using markermanager library in the google-maps-utility-library-v3 project as the easiest way.

1. Set up the MarkerManager

mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function () {
    loadMarkers();
});

2. Add markers to the MarkerManager

function loadMarkers() {
  var marker = new google.maps.Marker({
            title: title,
            position: latlng,
            icon: icon
   });
   mgr.addMarker(marker);
   mgr.refresh();
 }

3. To clear markers you just need to call the MarkerManger's clearMarkers() function

mgr.clearMarkers();
3
votes

You can do it this way too:

function clearMarkers(category){ 
  var i;       

  for (i = 0; i < markers.length; i++) {                          
    markers[i].setVisible(false);        
  }    
}
2
votes

I have just tried this with kmlLayer.setMap(null) and it worked. Not sure if that would work with regular markers but appears to work correctly.

2
votes

To clear of all the overlays including polys, markers, etc...

simply use:

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}

Here is a function that I wrote to do it form me on a map application:

  function clear_Map() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    //var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: HamptonRoads
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
2
votes

To remove all markers from map create functions something like this:

1.addMarker(location): this function used to add marker on map

2.clearMarkers(): this function remove all markers from map, not from array

3.setMapOnAll(map): this function used to add markers info in array

4.deleteMarkers(): this function Deletes all markers in the array by removing references to them.

// Adds a marker to the map and push to the array.
      function addMarker(location) {
        var marker = new google.maps.Marker({
          position: location,
          map: map
        });
        markers.push(marker);
      }


// Sets the map on all markers in the array.
      function setMapOnAll(map) {
        for (var i = 0; i < markers.length; i++) {
          markers[i].setMap(map);
        }
      }



// Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

// Deletes all markers in the array by removing references to them.
      function deleteMarkers() {
        clearMarkers();
        markers = [];
      }
2
votes

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.

1
votes

This is the method Google themselves use in at least one sample:

var markers = [];

// Clear out the old markers.
markers.forEach(function(marker) {
  marker.setMap(null);
});
markers = [];

Check Google sample for complete code example:

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

0
votes

I dont' know why, but, setting setMap(null) to my markers didn't work for me when I'm using DirectionsRenderer.

In my case I had to call setMap(null) to my DirectionsRenderer as well.

Something like that:

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);
    }
});
0
votes

Just walk over markers and remove them from map, empty maps markers array after that:

var markers = map.markers;
for(var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
}
map.markers = [];
0
votes

just clear Googlemap

mGoogle_map.clear();
0
votes

I've tried all of proposed solutions, but nothing worked for me while all my markers were under a cluster. Eventually I just put this:

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

In other words, if you wrap markers in a cluster and want to remove all markers, you call:

clearMarkers();
0
votes

Most voted answer at top is correct but in case if you have only one marker at a time (like I had in my situation) and every time you need to kill the previous location of that marker and add a new one then you don't need to create whole array of markers and manage it on every push and pop, you can simply just create a variable to store your marker's previous location and can set that to null on creation of new one.

// Global variable to hold marker location.

var previousMarker;

//while adding a new marker

    if(previousMarker != null)
previousMarker.setMap(null);

var marker = new google.maps.Marker({map: resultsMap, position: new google.maps.LatLng(lat_, lang_)});
previousMarker = marker;
-1
votes

You mean remove as in hiding them or deleting them?

if hiding:

function clearMarkers() {
            setAllMap(null);
        }

if you wish to delete them:

 function deleteMarkers() {
            clearMarkers();
            markers = [];
        }

notice that I use an array markers to keep track of them and reset it manually.

-1
votes

You need to set map null to that marker.

var markersList = [];    

function removeMarkers(markersList) {
   for(var i = 0; i < markersList.length; i++) {
      markersList[i].setMap(null);
   }
}

function addMarkers() {
   var marker = new google.maps.Marker({
        position : {
            lat : 12.374,
            lng : -11.55
        },
        map : map
       });
      markersList.push(marker);
   }
-1
votes

I found simple solution (I think) :

var marker = new google.maps.Marker();

function Clear(){
     marker.setMap(null);
}
-1
votes

I use a shorthand that does the job well. Just do

    map.clear();
-2
votes

if you use the gmap V3 plugin: $("#map").gmap("removeAllMarkers");

see: http://www.smashinglabs.pl/gmap/documentation#after-load