Okay, this is probably an embarrassing question as it’s almost certainly an issue of “pass by value” vs. pass by reference. I’m using Google Maps JavaScript API v3 and trying to populate a custom map markers of my own. Each marker corresponds to a location with lat, long, and a “comment” about that location, and is encoded as an object inside an array. However, while setting up the markers are fine in the loop, creating a listener to trigger dynamically updating another div with the comment about the location doesn’t seem to be working:
var myList = [ { lat: ..., lon: ..., title: ..., comment: ... }, { object repeats } ];
for (var i = 0; i < myList.length; i++) {
// bunch of code setting up the marker
var myMarker = new google.maps.Marker...
google.maps.event.addListener(myMarker, 'click', function()
{
$('myDiv').empty().append(myList[i].comment);
}
Now, everything works except for the code inside that anonymous function in the addListener. It seems the .comment isn’t passed by value but by reference (which makes sense), but the effect is that the .append() doesn’t append anything as the loop goes past the last index of the location array and when the .append is called it is trying to empty a null or undefined value. Any insight into how to fix this?
You have a closure issue (or a lack of closure).
I’m sorry I’m on my mobile phone so my answer is just a link:
https://developers.google.com/maps/documentation/javascript/events#EventClosures
See the Google example on how to bind events to objets when in a loop..
Thanks