function foreignCoordinatesArray(){
var coordinates = [];
$.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);
function success(ary) {
for(var a in ary){
var obj = ary[a];
coordinates.push(new google.maps.LatLng(obj.latitude, obj.longitude));
}
}
console.log(coordinates);
}
At the end coordinates will still be [] and not [{…},{…},…].
I guess this must be a problem with closures
How can I have my desired value in coordinates array?
It’s not a problem with closures but with asynchronous nature of JavaScript AJAX calls. The moment AJAX call response arrives (and your success function is called, propagating
coordinatesarray) it is way after you logged in that array – which was empty at that time.I guess you want to somehow return the
coordinatesfromforeignCoordinatesArray()function. As you can see you cannot usereturn:Instead you should pass a callback function that will receive
coordinates:BTW you should escape
$('#foreign_travel').val()before using it as part of the URL.