无法将标记添加到标记群集

时间:2016-05-26 13:33:02

标签: jquery google-maps google-maps-api-3

我尝试将我的标记添加到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);
                });
            });
        })();
    };
});  

1 个答案:

答案 0 :(得分:2)

markers变量在MarkerClusterer中使用时定义在范围之外。您可以将标记添加到仅存在于匿名markers内的不同(function(){..。要了解此问题,建议您查看thisthis文章。

修改

也!正如用户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);
                });
            });
        })();
    };
});