1

I need to return the variable result from the getNearRoutes function. Inside the routes function the array result has all the correct elements but when the function ends the array result is empty. I know this is a scope problem but I haven't been able to fix it, any help is appreciated.

Thanks in advance.

getNearRoutes: function(lat, lng){
    result = [];

    var routes = $.getJSON("js/storage/routes.json", function(json) {
        for(var i = 0; i < json.length; i++) {
            var obj = json[i];   

            for( var j = 0; j < obj.points.length ; j++){
                if (app.calculateDistance( obj.points[j].lat, obj.points[j].lng  , lat , lng) < 0.05) {

                    result.push(obj);
                    break;
                }

             }

         }

    });

    return result;
}
Alex Munoz
  • 155
  • 1
  • 8

1 Answers1

3

Since getJSON is async, you need a callback:

getNearRoutes: function(lat, lng, callback){
    var result = [];
    $.getJSON("js/storage/routes.json", function(json) {
        for(var i = 0; i < json.length; i++) {
            var obj = json[i];   

            for( var j = 0; j < obj.points.length ; j++){
                if (app.calculateDistance( obj.points[j].lat, obj.points[j].lng  , lat , lng) < 0.05) {
                    result.push(obj);
                    break;
                }
             }
         }
         callback(result);
    });
}

Then use the function:

getNearRoutes(lat, lng, function(result) {
    console.log(result); //data is here!
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157