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

时间:2012-07-25 02:14:54

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

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

2 个答案:

答案 0 :(得分: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 
                }) );
           }
    });
}

答案 1 :(得分: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);
}