开发者

How to delete markers from google map before painting new ones on idle event

I'm drawing markers on a google map after it's been panned or zoomed.

If the viewport has not totally changed than the 开发者_运维技巧markers that appeared before the move and should still appear after it are being painted on top of themselves again and again.

I know I have to delete all the markers from the map before the new markers are painted and I know I should be using marker.setMap(null);.

I just don't know how and where to fit it in my code.

google.maps.event.addListener(map, 'idle', showMarkers);

function showMarkers(){
    // get viewport bounds
    var southWestLat = map.getBounds().getSouthWest().lat();
    var southWestLng = map.getBounds().getSouthWest().lng();
    var northEastLat = map.getBounds().getNorthEast().lat();
    var northEastLng = map.getBounds().getNorthEast().lng();            

    var marker;

    $.ajax({
        type: "POST",
        url: "markers.php",
        dataType: "json",
        data: ({'southWestLat' : southWestLat , 'southWestLng' : southWestLng , 'northEastLat' : northEastLat , 'northEastLng' : northEastLng}),
        success: function(coordinatesMap){
            for (var id in coordinatesMap){
                if (coordinatesMap.hasOwnProperty(id)){                     
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng(coordinatesMap[id].lat,coordinatesMap[id].lng), 
                        map: map
                    });   
                }
            }
        }
    });         
}


For performance reasoning you don't want to clear all the markers; Only the ones no longer on the map. This can be accomplished by storing the marker in an array or object. On 'success' you want to check if a marker is already at the lat lng using your array/object. If so then don't add a new one, if not then add it. After you have finished processing the markers in the ajax request, remove the ones no longer visible on the map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜