首頁 >web前端 >js教程 >如何清除 Google Maps API v3 中的所有標記?

如何清除 Google Maps API v3 中的所有標記?

Susan Sarandon
Susan Sarandon原創
2024-11-15 11:58:03346瀏覽

How to Clear All Markers from Google Maps API v3?

Removing All Markers from Google Maps API v3

In Google Maps API v3, clearing all markers is slightly different from the approach used in v2. While map.clearOverlays() is no longer available, the following steps provide an efficient way to achieve the same effect:

1. Declare a Global Marker Array

var markersArray = [];

This array will store references to all markers on the map.

2. Define a Clear Overlays Function

There are two options for defining the clear overlays function:

Option A:

function clearOverlays() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray.length = 0;
}

Option B (Extends Google Maps API):

google.maps.Map.prototype.clearOverlays = function() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray.length = 0;
}

3. Add Markers to the Array

Before calling the clearOverlays() function, push each marker into the markersArray:

markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});

4. Call the Clear Overlays Function

Invoke the clearOverlays(); or map.clearOverlays(); function whenever needed to remove all markers from the map. This function iterates through the markersArray, sets the map property of each marker to null, and empties the array.

以上是如何清除 Google Maps API v3 中的所有標記?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn