Google Maps API v3: How to remove all markers?

后端 未结 30 3343
悲哀的现实
悲哀的现实 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:21

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

提交回复
热议问题