Google Maps API v3: How to remove all markers?

JavascriptHtmlGoogle MapsGoogle Maps-Api-3

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 3 - Javascript

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 4 - Javascript

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 5 - Javascript

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 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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 = [];
}

Solution 13 - Javascript

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.

Solution 14 - Javascript

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

Solution 15 - Javascript

You can do it this way too:

function clearMarkers(category){ 
  var i;       

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

Solution 16 - Javascript

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][1] 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][2], 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]: https://developers.google.com/maps/documentation/javascript/reference/data#Data [2]: https://developers.google.com/maps/documentation/javascript/reference/drawing#DrawingManager

Solution 17 - Javascript

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.

Solution 18 - Javascript

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

Solution 19 - Javascript

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

Solution 20 - Javascript

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 = [];
      }

Solution 21 - Javascript

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

Solution 22 - Javascript

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 = [];

Solution 23 - Javascript

just clear Googlemap

mGoogle_map.clear();

Solution 24 - Javascript

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

Solution 25 - Javascript

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;

Solution 26 - Javascript

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.

Solution 27 - Javascript

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

Solution 28 - Javascript

I found simple solution (I think) :

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

function Clear(){
     marker.setMap(null);
}

Solution 29 - Javascript

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

    map.clear();

Solution 30 - Javascript

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

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

Solution 31 - Javascript

I know that this maybe a simiple solution, but this is what I do

$("#map_canvas").html("");
markers = [];

Works every time for me.

Solution 32 - Javascript

Using this you can remove all marker from map .

map.clear();

This would help you ,it help me..

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmp_View Question on Stackoverflow
Solution 1 - JavascriptanonView Answer on Stackoverflow
Solution 2 - JavascriptPonsView Answer on Stackoverflow
Solution 3 - JavascriptMaiku MoriView Answer on Stackoverflow
Solution 4 - JavascriptrolingerView Answer on Stackoverflow
Solution 5 - JavascriptAndrewView Answer on Stackoverflow
Solution 6 - JavascriptJirapongView Answer on Stackoverflow
Solution 7 - JavascriptSphynxTechView Answer on Stackoverflow
Solution 8 - JavascriptjmbertucciView Answer on Stackoverflow
Solution 9 - JavascriptNguoi Viet NamView Answer on Stackoverflow
Solution 10 - JavascriptAdam StarrhView Answer on Stackoverflow
Solution 11 - JavascriptGregNView Answer on Stackoverflow
Solution 12 - JavascriptFreddieView Answer on Stackoverflow
Solution 13 - JavascriptmiddlewhereView Answer on Stackoverflow
Solution 14 - JavascriptCraig FruinView Answer on Stackoverflow
Solution 15 - Javascriptkolis29View Answer on Stackoverflow
Solution 16 - JavascriptMimoView Answer on Stackoverflow
Solution 17 - JavascriptbokorView Answer on Stackoverflow
Solution 18 - JavascriptWillView Answer on Stackoverflow
Solution 19 - JavascriptOgglasView Answer on Stackoverflow
Solution 20 - JavascriptRock StarView Answer on Stackoverflow
Solution 21 - JavascriptFelipe MiossoView Answer on Stackoverflow
Solution 22 - JavascriptkaiserView Answer on Stackoverflow
Solution 23 - JavascriptRejoylinLokeshwaranView Answer on Stackoverflow
Solution 24 - JavascriptGeka PView Answer on Stackoverflow
Solution 25 - JavascriptAdilView Answer on Stackoverflow
Solution 26 - JavascriptRobertoNView Answer on Stackoverflow
Solution 27 - JavascriptAdhumView Answer on Stackoverflow
Solution 28 - JavascriptaleXelaView Answer on Stackoverflow
Solution 29 - JavascriptUchenna NnodimView Answer on Stackoverflow
Solution 30 - Javascriptmgm8870View Answer on Stackoverflow
Solution 31 - JavascriptkronusView Answer on Stackoverflow
Solution 32 - JavascriptMayank GargView Answer on Stackoverflow