google maps v3 duplicate markers - using an array

2019-07-07 03:03发布

问题:

I'm not getting it: I have an array to manage my markers I add to a map. When I update the collection, the markers duplicate even though my markers array still only has the correct number of them in it.

I'm sure this is a really simple and stupid mistake on my part - but I'm not seeing it.

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

To me this looks like all is well, but the map keeps drawing 4 new markers on every dragend.... eeek!

回答1:

Modify your showMarkers() function to this:

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


回答2:

You can also compare new markers with your stored markers using some of following code (to display stored markers rather than new response marker):

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