0

I'm trying to return the variable coord from GetLocation, but it only returns undefined. Any help appreciated!

var coord = "";
function GetLocation(address) {

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { "address": address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            coord = ParseLocation(results[0].geometry.location);

            // This alert shows the proper coordinates 
            alert(coord);
        }
        else{ }

    });

    // this alert is undefined
    alert(coord);
    return coord;
}

function ParseLocation(location) {

    var lat = location.lat().toString().substr(0, 12);
    var lng = location.lng().toString().substr(0, 12);

    return lat+","+lng;
}
1
  • 2
    Does geocode() execute asynchronously? If so, coord value is not yet know at the time the function returns. Commented Aug 23, 2012 at 19:36

1 Answer 1

2

When you are returning coords from the outer function it is still in fact undefined. The inner function executes later when the asynchronous operation (if it wasn't asynchronous, the API would just give the result to you normally) is done.

Try passing a callback:

function GetLocation(address, cb) {

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { "address": address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            cb(ParseLocation(results[0].geometry.location));
        }
        else{ }

    });
}

You can then use it like so:

GetLocation( "asd", function(coord){
    alert(coord);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Ultimately I want to return the value from the function. yet if I do something like this var test = GetLocation( "asd", function(coord){ return coord; }); I don't think it'll work will it?
No you cannot do it, this is why it takes a function in the first place. If you could do that, they would just return it normally. Duh, right? :P You cannot get far with javascript if you just treat it as a linear sequence of commands anyway. Events, XHR requests etc are all asynchronous.
Got it, was just hoping there would be a way around it. Ta!

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.