2

I'm trying to build an array of latitudes and longitudes for start/end points for routing.

function parkRoute(){
    var start = $('#start').val();
    var end = $('#end').val();
    var points = [];
    function printPoints(points){
    console.log(points)
    }
    function getXY(add){
        geocoder.geocode( {'address': add + ", glendale, ca"}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0].geometry.location) {
                    var lon = results[0].geometry.location.kb;
                    var lat = results[0].geometry.location.jb;
                    points.push(lat,lon);
                    console.log(points)
                }
            }
        })          
    }
    getXY(start);
    getXY(end);
    printPoints(points);
}

It prints out an empty array first even though I'm calling another function to print them after the function to create the array.

[]                                      parks1.js:192

[34.1480811, -118.24759369999998]               parks1.js:201

[34.1480811, -118.24759369999998, 34.1851925, -118.27651679999997] parks1.js:201

What am I doing wrong?

James Montagne
  • 77,516
  • 14
  • 110
  • 130
marchWest
  • 375
  • 1
  • 8
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – James Montagne May 21 '13 at 14:49

2 Answers2

9

You are printing the array contents before pushing. The geocoding operation is asynchronous, so you have to print from the async callback.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
2

The problem is that you're not waiting for all the callbacks, which are asynchronous, to be executed.

You could do this :

var inProcess = 0; // number of tasks we're waiting for
function getXY(add){
    inProcess++; // increment the number of tasks
    geocoder.geocode( {'address': add + ", glendale, ca"}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0].geometry.location) {
                var lon = results[0].geometry.location.kb;
                var lat = results[0].geometry.location.jb;
                points.push(lat,lon);
                console.log(points)
            }
        }
        oneProcessIsDone();
    })          
}
function oneProcessIsDone() {
    if (--inProcess==0) { // decrement the number of tasks, and print the points if all are done
        printPoints(points);
    }
}
getXY(start);
getXY(end);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758