Google Maps API v3: How to remove all markers?

后端 未结 30 3311
悲哀的现实
悲哀的现实 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:16

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

提交回复
热议问题