I’ve been playing around with JavaScript and there’s something I don’t quite understand. I have this piece of code here:
$.getJSON('data.json', function(obj) {
for( var p in obj.List )
{
datas['id'] = obj.List[p].ListingId;
datas['area'] = area;
//console.log(datas);
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': datas['area'] }, function(results,status)
{
if(status == google.maps.GeocoderStatus.OK)
{
var latlng = new google.maps.LatLng(results[0].geometry.location.Ya, results[0].geometry.location.Za);
datas['latlng'] = latlng;
//console.log(datas);
}
});
}
});
Ok, now suppose the for loop runs 3 times. If we uncomment the first “console.log(datas)” line and run the page, in the console we see 3 “datas” objects with their own “id” and “area”. If I comment that first “console.log(datas)” and uncomment the second “console.log(datas)” in the geocode callback, when I run the code, all 3 “datas” objects are exactly the same in terms of “id”, “area”, and “latlng”. Whereas I expected the 3 “datas” objects would be different with their own latlngs.
Any ideas?
When is the function you pass to the
geocoder.geocodefunction run? If it’s not being run immediately then the for loop will run through all three times before the geocode function is run. That means thatdatas['id']anddatas['area']will have been set to the last iteration of the loop… in which case you need to capture the datas array inside a closure for the geocode function.In which case you’d need something like:
This prevents the datas variable as used by the anonymous function being updated by the for loop.