如何在空闲事件上绘制新标记之前从谷歌地图中删除标记



我正在谷歌地图上平移或缩放后绘制标记
如果视口与移动之前出现的标记相比没有完全改变,并且在一次又一次地在其顶部绘制之后仍然应该出现
我知道在绘制新标记之前,我必须删除地图上的所有标记,我知道我应该使用marker.setMap(null);
我只是不知道如何以及在哪里将其放入我的代码中。

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
                    });   
                }
            }
        }
    });         
}

对于性能推理,您不希望清除所有标记;只有那些不再在地图上的。这可以通过将标记存储在阵列或对象中来实现。在"成功"时,您需要使用您的数组/对象检查标记是否已经在latlng。如果是,那么就不要添加新的标记,如果不是,那么就添加它。在处理完ajax请求中的标记后,删除地图上不再可见的标记。

最新更新