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 = [];
II. Define a Function:
function clearOverlays() { for (var i = 0; i < markersArray.length; i++ ) { markersArray[i].setMap(null); } markersArray.length = 0; }
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; }
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(){});
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!