The code is supposed to add a click event where an infowindow opens on a marker with data from a PHP page and it "works" except the first infowindow opens blank (just says news in h1) and after that every other infowindow I open contains the stuff from the last marker. Can anyone tell me how to fix it?
//broken part
marker.addListener('click', function() {
$.getJSON('articles.php/GET?geo='+ marker.title)
.done(function(data, textStatus, jqXHR) {
$.each(data, function() {
contentString=contentString + '<li><a href=' + data[counter].link + '>' +data[counter].title + '</a></li>' ;
counter++;
});
});
contentString=contentString + '</ul></div>' ;
var infowindow= new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, marker);
counter=0 ;
contentString='<div align="center"><h1>news</h1><br></div><div align="left" colour="blue"><ul>';
});
$.getJSON is asynchronous, you need to use the data inside its call back function, when/where it is available (inside the .done
function).
marker.addListener('click', function() {
$.getJSON('articles.php/GET?geo='+ marker.title)
.done(function(data, textStatus, jqXHR) {
$.each(data, function() {
contentString=contentString + '<li><a href=' + data[counter].link + '>' +data[counter].title + '</a></li>' ;
counter++;
});
contentString=contentString + '</ul></div>' ;
var infowindow= new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, marker);
counter=0 ;
contentString='<div align="center"><h1>news</h1><br></div><div align="left" colour="blue"><ul>';
});
});