TL;DR
Why aren't you using .each()? You seem to be using jQuery anyway ...
function GetAddress() {
$.each(loationsArray, function(i, v) {
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ v.position.lat() + ',' + v.position.lng(),
function (result) {
v.address = result.results[0].formatted_address;
}
);
console.log(v);
});
}
... admittedly untested. But, if I've "transliterated" it correctly, your v
should be properly scoped in that implementation.
It's not that your callback can't see locationsArray
. If that were the case, your error would complain about locationsArray
or property 0 of locationsArray
not being defined.
The real trouble is, your callback refers to the i
from the for-loop's scope. After the last iteration, it actually increments i
to be locationsArray.length
. The loop-condition is tested, fails, and the loop is exited. But, i
is still locationsArray.length
-- a value that never existed. (Though, in a related problem, the collection could also be modified before the callback fires.)
Let's take an example:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(i, arr, arr[i]);
}, i * 100);
}
The Chrome console will show the following:
> 3 [1, 2, 3] undefined
> 3 [1, 2, 3] undefined
> 3 [1, 2, 3] undefined
To fix our example, we would "scope out" a reference to the particular item and put that in our callback. Something like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// create a scope
(function() {
var v = arr[i];
setTimeout(function() {
console.log(v);
}, i * 100);
})();
}
... And the console shows:
> 1
> 2
> 3