当前位置: 动力学知识库 > 问答 > 编程问答 >

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 can I do that using Google Maps API v3 ?

Thanks

网友答案:

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(){});
网友答案:

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.

网友答案:

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);
    }
}
网友答案:

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
网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: