Home > Web Front-end > JS Tutorial > body text

How to Remove All Markers in Google Maps API v3?

Linda Hamilton
Release: 2024-11-24 17:48:22
Original
610 people have browsed it

How to Remove All Markers in Google Maps API v3?

Removing Markers in Google Maps API v3: An Updated Approach

In Google Maps API v2, clearing map markers was straightforward using map.clearOverlays(). However, this method is not available in API v3. Here's a comprehensive guide to effectively remove all markers in v3.

The key is to utilize an array to store marker references and then iterate through the array to remove the markers from the map. The following steps outline this process:

I. Declare a Global Variable:

var markersArray = [];
Copy after login

II. Define a Function:

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

This function iterates over the markersArray, sets each marker's setMap property to null to remove it from the map, and then empties the array.

Alternatively, you can extend the Map prototype to include a clearOverlays method:

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

III. Push Markers into the Array:

Before removing the markers, ensure they are added to the markersArray. Use the following code:

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

IV. Call the Clear Overlays Function:

To execute the marker removal, call the clearOverlays() function or map.clearOverlays() wherever desired.

By following these steps, you can effectively remove all markers from your Google Maps API v3 application.

The above is the detailed content of How to Remove All Markers in 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