谷歌地图v3重复标记 - 使用数组来管理标记,但仍然得到重复

tim*_*tim 3 arrays google-maps google-maps-markers

我没有得到它:我有一个数组来管理我添加到地图中的标记.当我更新集合时,标记重复,即使我的标记数组仍然只有正确的数量.

我确信这对我来说是一个非常简单和愚蠢的错误 - 但我没有看到它.

m.viewMarkers = function(data){
    //ajax call to get latLng, returns an object with 4 markers
    showMarkers();
}

function showMarkers(){
    g.currentMarkers = []; // setting up my marker array
    $.each(g.markersCollection, function(i,item){ // jquery-iterate over the object from the ajax call
        g.currentMarkers.push( // adding markers to the array but purposely not drawing them on the map just yet
            new google.maps.Marker({
                position    : new google.maps.LatLng(item.lat, item.lng)
            });
        );
    });
$.each(g.currentMarkers, function(i,item){
    if( g.map.getBounds().contains( item.getPosition() ) ){ // checking if this marker is within the viewport
        item.setMap(g.map);
    }
    else {
        item.setMap(null); // i don't want to have invisible markers slowing down my map
    }
});
console.log(g.currentMarkers.length); // tells me it's 4, just as expected
}

google.maps.event.addListener(g.map, 'dragend', function() {
    m.viewMarkers();
});
Run Code Online (Sandbox Code Playgroud)

对我而言,这看起来一切都很好,但是地图一直在每个dragend.... eeek 上绘制4个新标记!

Eng*_*eer 6

将您的showMarkers()功能修改为:

function showMarkers(){
    //Removing old markers from the Map,if they are exist
    if(g.currentMarkers && g.currentMarkers.length !== 0){            
        $.each(g.currentMarkers, function(i,item){
            item.setMap(null);
        });
    }
    g.currentMarkers = []; // setting up my marker array
    $.each(g.markersCollection, function(i,item){ 
           var expectedPosition = new google.maps.LatLng(item.lat, item.lng);
           //No need to add marker on the Map if it will not visible on viewport, 
           //so we check the position, before adding 
           if(g.map.getBounds().contains(expectedPosition)){
                g.currentMarkers.push(new google.maps.Marker({ 
                    position : expectedPosition 
                }) );
           }
    });
}
Run Code Online (Sandbox Code Playgroud)