Home >Web Front-end >JS Tutorial >How to Clear All Markers from Google Maps API v3?

How to Clear All Markers from Google Maps API v3?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 11:58:03341browse

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.

The above is the detailed content of How to Clear All Markers from Google Maps API v3?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn