0

I'm trying to get location coordinates via the google maps javascript api, which happens asynchronously.

Here is my function for retrieving:

function getCoords(input_address)
{
    var geocoder = new google.maps.Geocoder();
    var addr = {
        address: input_address
    };
    var callback = function(result, status)
    {
        if (status == "OK") {
            var coords = result[0]['geometry']['location'];
            console.log(coords.toUrlValue());
        }
    };
    geocoder.geocode(addr,callback);
}

I want to submit the coordinates along with the rest of a form via an ajax function.

However, testing out the following:

form.submit(function(event){
    event.preventDefault();
     var addr = $("input[type='text']").val();
     getCoords(addr);
     console.log('should wait');
});

Outputs:

should wait
coordinates

Is there a way to make sure the getCoords function completes before the next instruction is executed?

tgun926
  • 1,573
  • 4
  • 21
  • 37
  • Use a callback or a promise. – Jason P Mar 22 '14 at 03:39
  • 2
    This is a FAQ. When you typed your title Stack Overflow showed you a bunch of possible same questions. The third one has the answer. http://stackoverflow.com/questions/2768293/waiting-on-multiple-asynchronous-calls-to-complete-before-continuing. See also http://stackoverflow.com/questions/14011619/how-to-know-when-multiple-asynchronous-calls-to-complete-then-call-another-comma?rq=1 – Phrogz Mar 22 '14 at 03:40
  • @Phrogz Forgive my ignorance, bu't isnt that answer specifically for ajax calls? – tgun926 Mar 22 '14 at 06:45

1 Answers1

1

Use the callback function for this purpose, do your other job after executed geocoder.geocode(); something like

function getCoords(input_address){
    ......
    ......
    geocoder.geocode(addr, function (){
          doYourJobNow(); //as suggested by tgun926
     });

}

function doYourJobNow(){
    console.log('should wait');
}

//result would be
//coordinates
//should wait
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
  • `geocoder.geocode()` is the asynchronous task, so doYourJobNow() would have to be run inside `geocode()`'s callback function. If you edit that, I'll mark this answer as correct. – tgun926 Mar 26 '14 at 10:39
  • Please have a look udpdated answer, If I got wrong then please make me correct. – Suman Bogati Mar 26 '14 at 14:15