Google Maps API v3 - How to clear overlays?
In Google Maps API v2, I was using map.clearOverlays()
to remove the marker and draw them again.
How开发者_如何学Go can I do that using Google Maps API v3 ?
Thanks
This is good one:
http://apitricks.blogspot.com/2010/02/clearoverlays-in-v3.html
Article in case the link dies:
clearOverlays() in V3
There is no clearOverlays() in API v3. Some practices have been presented. I think this is the simpliest so far.
Push all the overlays in an array when created (as usual). Following code will clear both map and the array:
while(overlays[0])
{
overlays.pop().setMap(null);
}
pop() method of an array removes the last element of an array, and returns that element. 'while' keeps that happening as long as there are elements in the array. When overlays[0] does not exist anymore, the mission is completed and code will proceed.
See here for details on the various options open to you but you now have to iterate through the markers and remove them individually. Your code should look something like this:
var markers = [];
function clearOverlays() {
while(markers.length) { markers.pop().setMap(null); }
markers.length = 0;
}
markers.push(marker);
google.maps.event.addListener(marker,"click",function(){});
I found another solution and it works very good it will remove all overlays that exist on the map
gmap.overlayMapTypes.setAt( 0, null);
while gmap is your map object
You can take a look at the Google Maps documentation as it show simple deleteOverLays method http://code.google.com/apis/maps/documentation/javascript/overlays.html
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
How about this one? I don't want to use the .setMap(null), because I don't know a better way to initiate the polyShape again.
polyShape = new google.maps.Polygon(
{
strokeColor : '#000000',
strokeOpacity : 0.3,
strokeWeight : 1,
fillColor : "#000000",
fillOpacity : 0.26,
geodesic : true
});
Then.. iterate through the path to remove it.
var path = new google.maps.MVCArray;
/**
* Delete all points inside Map
*/
function clearMap()
{
//clear markers
for (var i = 0; i < markers.length; i++)
{
markers[i].setMap(null);
}
markers = [];
//clear polygon, still finding more elegant way
while (polyShape.getPath().length)
{
path.removeAt(0);
}
}
The overlayMapTypes
object brings a clear method:
map.overlayMapTypes.clear()
Whereas map is your Google Maps object.
If you cannot find the method in your API version, you can resort to the following source of clear
:
clear = function() {
for (; this.get("length");) this.pop()
};
You can find a good example provided by Google here: http://code.google.com/p/gmaps-samples-v3/source/browse/trunk/clear-all-overlays/clear-all-overlays.html
Basically the idea is the remove
- Markers
- Polygons
- and Polylines separately
精彩评论