我正在尝试使用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回调函数中执行此操作,但我看不到其他任何区别。我在地图上正常显示标记,但没有聚类效果。
答案 0 :(得分:0)
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);