我尝试将我的标记添加到MarkerCluster,我有以下代码,我将每个Marker
推送到markers
数组。然后我声明markerCluster
并添加markers
数组和地图。但是我的MarkersClusterer永远不会显示,有人可以建议为什么会这样吗?
map = new google.maps.Map($('#map_canvas')[0], myOptions);
infowindow = new google.maps.InfoWindow();
markerCluster = new MarkerClusterer(map, markers);
//do ajax request, add marker on success
jQuery.post(ajaxurl, data, function(response) {
for (key in response) {
if(response[key]["post_code"] === undefined ){
return;
}
(function () {
var markers = [];
var address = response[key]["address"];
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+response[key]["post_code"]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var Marker = new google.maps.Marker({
position: latlng,
map: map,
content: address
});
markers.push(Marker);
google.maps.event.addListener(Marker, 'click', function () {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
});
})();
};
});
答案 0 :(得分:2)
markers
变量在MarkerClusterer
中使用时定义在范围之外。您可以将标记添加到仅存在于匿名markers
内的不同(function(){..
。要了解此问题,建议您查看this或this文章。
修改强>
也!正如用户vyx.ca所指出的,MarkerClusterer
具有addMarker()
方法,即向群集器添加标记的advised way。我的代码现在反映了这一变化。
有评论的部分代码引用了这些变化:
var markers = []; //HERE!!
map = new google.maps.Map($('#map_canvas')[0], myOptions);
infowindow = new google.maps.InfoWindow();
markerCluster = new MarkerClusterer(map, markers);
jQuery.post(ajaxurl, data, function(response) {
for (key in response) {
if(response[key]["post_code"] === undefined ){
return;
}
(function () {
//REMOVE THIS !! var markers = [];
var address = response[key]["address"];
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+response[key]["post_code"]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var Marker = new google.maps.Marker({
position: latlng,
map: map,
content: address
});
//Changed to line below - markers.push(Marker);
markerCluster.addMarker(Marker);
google.maps.event.addListener(Marker, 'click', function () {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
});
})();
};
});