In version 2 of the Google Maps API, removing all map markers was as simple as using map.clearOverlays(). However, this method is no longer available in API v3. This comprehensive guide will guide you through the steps to efficiently remove all markers from your map:
Start by declaring a global variable to store an array of your markers:
var markersArray = [];
Create a function named clearOverlays() to iterate through the marker array and set each marker's map to null:
function clearOverlays() { for (var i = 0; i < markersArray.length; i++) { markersArray[i].setMap(null); } markersArray.length = 0; }
OR
Alternatively, you can define the function as a prototype method of google.maps.Map:
google.maps.Map.prototype.clearOverlays = function() { for (var i = 0; i < markersArray.length; i++) { markersArray[i].setMap(null); } markersArray.length = 0; }
Before calling the clearOverlays() function, make sure to push each marker to the markerArray as you add it to the map. Remember to add an event listener to each marker for interactivity:
markersArray.push(marker); google.maps.event.addListener(marker, "click", function() {});
Finally, call the clearOverlays() or map.clearOverlays() function whenever you need to remove all markers from the map.
Using these steps, you can now effectively remove all markers from your Google Maps API v3 application.
The above is the detailed content of How to Remove All Markers from a Google Maps API v3 Application?. For more information, please follow other related articles on the PHP Chinese website!