gpt4 book ai didi

javascript - googlemaps api MarkerClusterer问题

转载 作者:行者123 更新时间:2023-12-04 02:03:55 27 4
gpt4 key购买 nike

我正在尝试使用 map API MarkerClusterer功能,但运气不好:

var markersArray = [];

function getMarkers(hours) {//5

if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}

image = '/images/site/tw.png';

$.ajax({
url: "updateMarkers",
type:"POST",
data:{"hours": hours},
success: function(data){
data = $.parseJSON( data );
if (data.Locations.length>0) {//2
for (i=0; i<data.Locations.length; i++) {//1
loc = new google.maps.LatLng(data.Locations[i].lat, data.Locations[i].lng);

marker = new google.maps.Marker({
position: loc,
map: map,
icon: image,
html: content
});

markersArray.push(marker);

infowindow = new google.maps.InfoWindow({
content: "holding..."
});

google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
infowindow.setContent(this.html);
});
}//1
}//2
}
});

var markerCluster = new MarkerClusterer(map, markersArray);

}//5

getMarkers(24);

我看了我能找到的所有示例,尽管我试图在ajax回调函数中执行此操作,但看不到其他区别。我得到的标记在 map 上正常显示,但是没有聚类效果。

最佳答案

Ajax是异步的。发生的情况是您在回调函数完成之前创建了MarkerClusterer,因此没有标记被推到全局数组markersArray上。这只是我的头上没有进行任何测试,但是看看是否可以解决问题。

var markersArray = [], markerCluster;

function getMarkers(hours) {//5

if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}

image = '/images/site/tw.png';

$.ajax({
url: "updateMarkers",
type:"POST",
data:{"hours": hours},
success: function(data){
data = $.parseJSON( data );
if (data.Locations.length>0) {//2
for (i=0; i<data.Locations.length; i++) {//1
loc = new google.maps.LatLng(data.Locations[i].lat, data.Locations[i].lng);

marker = new google.maps.Marker({
position: loc,
map: map,
icon: image,
html: content
});

markersArray.push(marker);

infowindow = new google.maps.InfoWindow({
content: "holding..."
});

google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
infowindow.setContent(this.html);
});
}//1

//Create the Cluster AFTER all markers are pushed into the markersArray, and make sure it's called within the callback function
markerCluster = new MarkerClusterer(map, markersArray);
}//2
}
});

}//5

getMarkers(24);

关于javascript - googlemaps api MarkerClusterer问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6120658/

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