Accessing loop iteration in a sub-function?

Posted by DisgruntledGoat on Stack Overflow See other posts from Stack Overflow or by DisgruntledGoat
Published on 2010-01-19T18:19:50Z Indexed on 2010/05/21 8:20 UTC
Read the original article Hit count: 163

I'm using the Google Maps API to plot several points on a map. However, in the click event function below, i is always set to 4, i.e. its value after iterating the loop:

// note these are actual addresses in the real page
var addresses = new Array( "addr 1", "addr 2", "addr 3", "addr 4" );

for (var i = 0; i < addresses.length; i++) {
    geocoder.getLatLng(addresses[i], function(point) {
        if (point) {
            var marker = new GMarker(point);
            map.addOverlay(marker);
            map.setCenter(point, 13);

            GEvent.addListener(marker, "click", function() {
                // here, i=4
                marker.openInfoWindowHtml("Address: <b>" + addresses[i] + "</b>");
            });
        }
    });
}

So when the marker displays it's using addresses[4] which is undefined. How do I pass the correct value of i to the function?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about google-maps