Reputation: 1320
I'm attempting to add my markers to a MarkerCluster, I have the following code, I push each Marker
to the markers
array. I then declare markerCluster
and add in the markers
array and the map. However my MarkersClusterer never display, could anyone suggest why this is?
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);
});
});
})();
};
});
Upvotes: 0
Views: 1407
Reputation: 5383
Your markers
variable is defined outside of the scope when it's used in MarkerClusterer
. You add markers to different markers
which only exists inside the anonymous (function(){..
. To understand this problem, I suggest you to take a look at this or this article.
EDIT
ALSO! As user vyx.ca pointed out, MarkerClusterer
has addMarker()
method which is the advised way of adding markers to the clusterer. My code now reflects the change.
There are commented parts of code referring to the changes:
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);
});
});
})();
};
});
Upvotes: 2