I have been searching SE for a good 2 hours now trying to solve the reason why I am losing the value of my 'locations' variable. Leveraging closure looked like the best solution, but in the context of the callback function below I couldn't figure out how to implement it properly.
Can someone lend a little insight regarding this phenomena how how exactly it could be remedied? If there are any key terms please point them out so I can research them accordingly.
Thank you for your time.
The code in question:
for (var i = 0; i < locations.length; i++) {
geocoder.geocode({
'address': locations[i] // Returns location as expected
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(locations[i]); // returns undefined
}
})
}
To clarify, I have already seen the closest post similar to this one: When using callbacks inside a loop in javascript, is there any way to save a variable that's updated in the loop for use in the callback? but I am unable to make it work within the scope of the situation.
Thanks again.