Adding multiple markers with infowindows (Google Maps API)
Javascript has a language structure called "closures". Closures are functions (such as the function() {} you declare above to deal with click listener) which capture references to external variables.
There are plenty of resources which explain them better than I can, which I suggest you consult, but here's my best attempt:
In this block here:
google.maps.event.addListener(markers[key], 'click', function() {
infowindows[key].open(map, markers[key]);
});
Because "key" is already defined as an external variable, the function will capture a reference to that variable. So where you expect:
infowindows["helloworld"]
Javascript will instead interpret this as:
infowindows[reference to key]
When you click on a marker, it looks up "reference to key" to see what the current value of key is. Because this probably won't happen until your loop has finished, key will be equal to whatever the last key in your data.markers object is. And it will be equal to that value for EVERY click listener you added.
The solution, as you point out, is to wrap this in an anonymous function to get Javascript to evaluate the value of "key" at the time that the click listener is added.
google.maps.event.addListener(markers[key], 'click', function(innerKey) {
return function() {
infowindows[innerKey].open(map, markers[innerKey]);
}
}(key));
This works fine for me! Just add a new property to marker object, this property contains the infowindow object.
var mytext = 'Infowindow contents in HTML'
var myinfowindow = new google.maps.InfoWindow({
content: mytext
});
var marker = new google.maps.Marker({
position: mypos,
map: mymap,
icon: myicon,
title: mytitle,
infowindow: myinfowindow
});
google.maps.event.addListener(marker, 'click', function() {
this.infowindow.open(map, this);
});
There is a slightly simpler way to accomplish this. you can add a custom attribute to your marker (the info window's index) and refer to it in the callback function. Example below:
markers = Array();
infoWindows = Array();
for(var i in earthquakes)
{
var location = new google.maps.LatLng(earthquakes[i].geolat, earthquakes[i].geolong);
var marker = new google.maps.Marker({
position : location,
map : map,
animation : google.maps.Animation.DROP,
infoWindowIndex : i //<---Thats the extra attribute
});
var content = "<h3>" + earthquakes[i].title + "<h3>" +
"<a data-ajax='false' target='_blank' href='" + earthquakes[i].link + "'>Link to shakemap.</a>";
var infoWindow = new google.maps.InfoWindow({
content : content
});
google.maps.event.addListener(marker, 'click',
function(event)
{
map.panTo(event.latLng);
map.setZoom(5);
infoWindows[this.infoWindowIndex].open(map, this);
}
);
infoWindows.push(infoWindow);
markers.push(marker);
}