[google maps API] 清除所有 marker

  1. var markers = [];   
  2.     window.onload = function () {   
  3.         var mapOptions = {   
  4.             center: new google.maps.LatLng(21.0000, 78.0000),   
  5.             zoom: 5,   
  6.             mapTypeId: google.maps.MapTypeId.ROADMAP   
  7.         };   
  8.         var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);   
  9.     
  10.         //Attach click event handler to the map.   
  11.         google.maps.event.addListener(map, 'click'function (e) {   
  12.     
  13.             //Determine the location where the user has clicked.   
  14.             var location = e.latLng;   
  15.     
  16.             //Create a marker and placed it on the map.   
  17.             var marker = new google.maps.Marker({   
  18.                 position: location,   
  19.                 map: map   
  20.             });   
  21.     
  22.             //Attach click event handler to the marker.   
  23.             google.maps.event.addListener(marker, "click"function (e) {   
  24.                 var infoWindow = new google.maps.InfoWindow({   
  25.                     content: 'Latitude: ' + location.lat() + '<br />Longitude: ' + location.lng()   
  26.                 });   
  27.                 infoWindow.open(map, marker);   
  28.             });   
  29.     
  30.             //Add marker to the array.   
  31.             markers.push(marker);   
  32.         });   
  33.     };   
  34.     function DeleteMarkers() {   
  35.         //Loop through all the markers and remove   
  36.         for (var i = 0; i < markers.length; i++) {   
  37.             markers[i].setMap(null);   
  38.         }   
  39.         markers = [];   
  40.     };  

主要就是把 marker 都存到陣列後再一次刪掉。

Source

留言