On Dec 17, 3:29 pm, Evan M <[email protected]> wrote:
> This is the part of my code I am having troubles with, in this example
> there are 2 addresses in the addressArray.

getLocations is asynchronous. That means that it fires off a request
when that line is encountered, and then at some point later the
callback function fires.

So the code exection is
 geocoder.getLocations(addressArray[0])
 geocoder.getLocations(addressArray[1])
 geocoder.getLocations(addressArray[2])

At this point the value of i is 2. Then the getLocations response for
i=0 comes back and runs the callback function. The first line is
  alert(i)
and i is 2. The same thing happens for the next two callbacks.

One way around this, ensuring closure on i, is to use a helper
function in much the same way as a createMarker function:

function doGeocode(i,a) {
  // i is local to this function
  geocoder.getLocations(a,function(result) {
    // i has its local value in the callback function
    ... }
  }
for (i=0;i<numAddresses;i++) {
  doGeocode(i, addressArray[i])
  }

This binds the loop-counter i into the callback function. In this case
it would probably be clearer *not* to use i as the loop counter as
well as an argument in doGeocode, just to emphasise that they are not
the same variable.

Andrew
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Google Maps API" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/Google-Maps-API?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to