0

I'm trying to return longitude and latitude from this function, I can console.log both of them, but when I try to return one of them, I get undefined.

How can I return latitude, longitude?

function latLong(location) {
    var geocoder = new google.maps.Geocoder();
    var address = location;
    var longitude;
    var latitude;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        console.log(longitude);
    });
}

2 Answers 2

4

The geocoder is asynchronous, and you can't return data from an asynchronous function, you could however use a callback

function latLong(location, callback) {
    var geocoder = new google.maps.Geocoder();
    var address = location;
    var longitude;
    var latitude;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();

            callback(latitude, longitude);

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

and to use it do

 latLong(location, function(lat, lon)  {
     // inside this callback you can use lat and lon
 });
Sign up to request clarification or add additional context in comments.

Comments

1

You don't.

The generally used technique is to pass a callback to latLong function as a parameter, and run this function when you receive the result.

Something like:

function latLong(location, callback) {

    var geocoder = new google.maps.Geocoder();
    var address = location;
    var longitude;
    var latitude;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            callback(latitude, longitude);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        console.log(longitude);
    });
}

Comments

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.