3

我不明白:我有一个数组来管理我添加到地图的标记。当我更新集合时,即使我的标记数组中仍然只有正确数量的标记,标记也会重复。

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

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

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

4

2 回答 2

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 
                }) );
           }
    });
}
于 2012-07-25T08:49:36.673 回答
0

您还可以使用以下代码将新标记与存储的标记进行比较(以显示存储的标记而不是新的响应标记):

var latlng1,latlng2;
for (var i=0; i< storedmarker.length; i++){
    //Removing old markers from the Map,if they are exist with storedmarkers
    latlng1 = storedmarker[i].getPosition();
    for (var j=0; j< newmarkers.length; j++) {
      latlng2 = newmarkers[j].getPosition();
      if(latlng1.equals(latlng2)){
        newmarkers[j].setMap(null);
      }
    }

    //Set Marker
    storedmarker[i].setMap(map);
}
于 2016-11-17T12:43:24.137 回答