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
Release: 2024-11-15 11:58:03
Original
337 people have browsed it

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 = [];
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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(){});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template