Search code examples
javascriptvariablesundefinedexecution

Google reverse geocode return variable


I have this code:

var reverseGeo = function (latitude, longitude){

var address1;

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

var location = new google.maps.LatLng(latitude, longitude);

geocoder.geocode({'latLng': location}, function(results, status){
    if(status === google.maps.GeocoderStatus.OK){
        if(results[0]){
            address1 = results[0].formatted_address;
            //console.log(address1);

        }
        else{
            console.log(status);
        }

    }

});

console.log(address1);
};

The first console.log(); that is commented out is correct. It contains the formatted address. The second console.log() at the bottom is undefined. What am I missing here? Furthermore, I need this address1 variable to be returned to a parent javascript file that is directly calling this script. No matter what I try though, i get undefined everywhere except for locally in geocoder.geocode();


Solution

  • You are having an issue with understanding the asynchronous capabilities of javascript and callback functions

    geocoder.geocode function accepts a callback function as it's 2nd parameter. This function will be called asynchronously whenever the address is retrieved.

    Your console.log at the end will not work because after the geocoder.geocode() function has been called, the program will not wait for the callback function to be called and rather immediately executes the next instructions. In this case address1 variable will not have been populated yet.

    What you are actually looking for is a function that accepts your location and a callback function. Something like this:

    function getAddress(location, callback){
        geocoder.geocode({'latLng': location}, function(results, status){
            if(status === google.maps.GeocoderStatus.OK){
                if(results[0]){
                    var address1 = results[0].formatted_address;
                    callback(address1);
                }
            }
        });
    }
    

    Now from the other file which you want to use this address in, you can call this function like this:

    var location = new google.maps.LatLng(latitude, longitude);
    getAddress(location, function(address)
    {
        console.log(address);
    });
    

    And here, after the address has been retrieved, your function that you have defined accepting the address will be called and the address variable will be available to you.