首頁 > web前端 > js教程 > 主體

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

Susan Sarandon
發布: 2024-11-15 11:58:03
原創
260 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板