0

I have the following, but the title just repeats the same. How would I be able to get the usage of title inside the getJSON function?

for (var x = 0; x < temp_addresses.length; x++) {
    var title = temp_addresses[x].title;
    var jqxhr = $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+temp_addresses[x].gps+'&sensor=false', null, function(data) {
        var p = data.results[0].geometry.location
        latlng = new google.maps.LatLng(p.lat, p.lng);
        console.log(title+' - '+latlng);
    });
}
ngplayground
  • 20,365
  • 36
  • 94
  • 173
  • See http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example or http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue – Crescent Fresh May 17 '14 at 21:46
  • @CrescentFresh this doesn't cover my Q – ngplayground May 17 '14 at 21:53
  • I suspect it does, in a roundabout fashion. How are you currently not able to get at the `title` variable? – Evan Knowles May 17 '14 at 22:04
  • This is a actually a closer duplicate to http://stackoverflow.com/q/19701823/218196 (found with [`[jquery] ajax loop variable`](http://stackoverflow.com/search?q=%5Bjquery%5D+ajax+loop+variable)), but the other one has a better explanation IMO. – Felix Kling May 17 '14 at 22:37

1 Answers1

2

This is a closure issue.

Try this:

for (var x = 0; x < temp_addresses.length; x++) {
    var title = temp_addresses[x].title;
    var url = 'http://maps.googleapis.com/maps/api/geocode/json?address='+temp_addresses[x].gps+'&sensor=false';
    var jqxhr = performReq(title,url);
}

function performReq(title,url){
    return $.getJSON(url, null, function(data) {
        var p = data.results[0].geometry.location
        latlng = new google.maps.LatLng(p.lat, p.lng);
        console.log(title+' - '+latlng);
    });
}
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99