Google Maps API v3: How to remove all markers?

后端 未结 30 3335
悲哀的现实
悲哀的现实 2020-11-22 05:36

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

30条回答
  •  萌比男神i
    2020-11-22 06:16

    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

    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)

提交回复
热议问题