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?

1

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

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);

3 Comments

I'd transfer my +8 to your answer if I could.
I'd steal them if I could :)
Thanks for the help and to you too @bfavaretto. I got that I wasn't waiting till the processes were done, I just couldn't figure out at what point in the code that the process was finished. Thanks for explaining it and providing an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.