Reputation: 970
I'm loading markers from a database in XML format and breaking it out using a for() loop but I have an addListener event 'click' that contains an AJAX call I'm having trouble with. I'm trying to populate the content of my infoWindow with the data pulled down in the ajax call.
Here is a copy of my code inside the for() loop:
var mkID = mk[i].getAttribute("id");
marker = new google.maps.Marker({
position: point,
map: map,
icon: "/img/icon.png",
title: "Click to Show"
});
infoWindow = new google.maps.InfoWindow({
content: "<i class='fa fa-spinner fa-spin fa-lg' style='color: #FFA46B;' title='Loading...'></i> Loading..."
});
markerArray.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, infoWindow, mkID) {
return function() {
if(infoWindow) {
infoWindow.close();
}
infoWindow.open(map, marker);
$.ajax({
url: '/map-info-ajax.html?id=' + mkID,
success: function(data) {
infoWindow.setContent(data);
}
});
};
})(marker, infoWindow, mkID));
I tried changing this:
infoWindow = new google.maps.InfoWindow({
content: "<i class='fa fa-spinner fa-spin fa-lg' style='color: #FFA46B;' title='Loading...'></i> Loading..."
});
to just this:
infoWindow = new google.maps.InfoWindow();
But the info windows are just coming up blank now when data does contain 'xyzzy ya ya ya'. Can anyone see what I'm doing wrong here?
Regards, Vince
Upvotes: 2
Views: 5222
Reputation: 970
Finally got this working. Here is what the code looks like now.
var mkID = mk[i].getAttribute("id");
marker = new google.maps.Marker({
position: point,
map: map,
icon: "/img/icon.png",
title: "Click to Show"
});
infoWindow = new google.maps.InfoWindow({
content: "<i class='fa fa-spinner fa-spin fa-lg' style='color: #FFA46B;' title='Loading...'></i> Loading..."
});
markerArray.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, infoWindow, mkID) {
return function() {
if(infoWindow) {
infoWindow.close();
}
infoWindow.open(map, marker);
infoWindowAjax(mkID, function(data) {
infoWindow.setContent(data);
});
};
})(marker, infoWindow, mkID));
And the infoWindowAjax() function that it calls.
function infoWindowAjax(mkID, callback) {
return $.ajax({
url: '/map-info-ajax.html?id=' + mkID
})
.done(callback)
.fail(function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
}
I had to move the ajax call to it's own function and use a callback to get the information back to where I could use it once it had run it's course.
PS: I was using jQuery v2.1.1.
PPS: If the data returned is just simple raw text, even UTF-8 content, make sure the PHP template header is set like header("Content-type: text/html; charset=UTF-8");. One little bug I ran into was that I had mine set incorrectly to text/xml.
Upvotes: 4