ChatGPT解决这个技术问题 Extra ChatGPT

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.

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.html
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...
The solutions suggested here appear to be broken as of 2010/07/29. I wish I had a working version to suggest instead.
The highest rated answer is wrong. View source on this example to see how to do it: google-developers.appspot.com/maps/documentation/javascript/…

8
8 revs, 8 users 58% anon

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


for..in loop with an Array? this cant be good surely .. ? ..see: stackoverflow.com/questions/500504/…
Alternatively you can hide markers using the marker.setVisible(false)
The markers are still kept in the array though so it will grow larger and larger. Would suggest clearing the array as well after the loop
you can always set markersArray to an empty array instead of setting its length, which i find kind of odd: markersArray = [];
I'd use a while approach for processing the array: while(markersArray.length) { markersArray.pop().setMap(null); }. No need to clear the array after that.
m
mooreds

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


The way I finally got it working was to iterate through the markers collection where I stored them and use setMap(null)
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.
@Nick: add 'delete this.markers[i];' after the setMap(null) bit.
This question is answered in the documentation now. code.google.com/apis/maps/documentation/javascript/…
Who even uses new Array(); ?
C
Community

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)


+1 From me. But your answer would be better if you included the wrapper to call addMarker automatically!
I assume you're referring to Andrews answer actually. Would you show with code what you'd do different and why. Thanks
Meh sorry for delay, I was holding back from posting code because I had no way to quickly test it.
Thanks Maiku. Though, I don't understand - how do I add a new marker in your example. Again, many many thanks!
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! :(
r
rolinger

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.

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


+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 :).
@Maiku Mari, would you show with code what you'd do different and why. Thanks
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/…
I believe it came from here lootogo.com/googlemapsapi3/markerPlugin.html
-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.
J
Jirapong

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

S
SphynxTech

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.


j
jmbertucci

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.


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


Please read the help regarding the formatting of code on SO
A
Adam Starrh

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

G
GregN

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


C
Crisoforo Gaspar

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

G
Guido

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.


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); }
C
Craig Fruin

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

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.
C
Crisoforo Gaspar

You can do it this way too:

function clearMarkers(category){ 
  var i;       

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

M
Mimo

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.


b
bokor

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.


F
Fraser

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

wouldn't this also reset the map ? suppose if the user had dragged the map to a new area ?
O
Ogglas

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


R
Rock Star

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

F
Felipe Miosso

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

k
kaiser

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

R
RejoylinLokeshwaran

just clear Googlemap

mGoogle_map.clear();

G
Geka P

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

A
Adil

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;

R
RobertoN

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.


A
Adhum

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

a
aleXela

I found simple solution (I think) :

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

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

m
mgm8870

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

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


U
Uchenna Nnodim

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

    map.clear();