gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:00:19 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

将您的 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
}) );
}
});
}

关于arrays - 谷歌地图 v3 重复标记 - 使用数组来管理标记但仍然重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com