-2

I just can't find what's wrong with this bit of code:

function getLocationName(latitude, longitude) {
    if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) {
        return false;
    }

    var locationName;
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude)

    // Reverse Geocoding using google maps api.
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                locationName = results[1].formatted_address;
                alert(locationName);
            }
            else {
                locationName = "Unknown";
            }
        }
        else {
            locationName = "Couldn't find location. Error code: " + status;
        }
    });
    alert(locationName);
    return locationName;

}

I call this from a jquery event handler like this:

$("#id").on("event", function (event, ui) {
    $("#userLocation").text(getLocationName(latitude, longitude));
});

Weird part is that the first alert gets the correct value of 'locationName' but the second one always returns 'undefined'. I tried initializing the variable with a value and in that case the first alert again returned the correct location name but the second one returned the initialization value. This gives me a notion that this might be a variable scope related problem but I just can't figure what.

PS. I don't have any other variables (local/global) by the same name.

Update: The alert works fine now (thanks to Lwyrn's answer) but the return value is still wrong. I've followed the answers in the linked SO question and still I couldn't 'return' the right value. The alert did work fine.

reggaemahn
  • 6,272
  • 6
  • 34
  • 59
  • 4
    It's not due to variable scope, it's due to asynchronous nature of the code. http://stackoverflow.com/questions/2993563/how-do-i-return-a-variable-from-google-maps-javascript-geocoder-callback?rq=1 – DCoder Jul 28 '13 at 10:44
  • 1
    Then you didn't read the linked question carefully. There is **no way** to *return* a value from an asynchronous action, you need to use a callback. (OK, if you are making the AJAX call yourself you can make it synchronous instead of asynchronous, but that is just wrong for a lot of reasons.) – DCoder Jul 28 '13 at 11:29

1 Answers1

4

You have to move "alert(locationName);" into the geocoder.geocode callback. Because geocoder.geocode executes an AJAX request. When you throw the alert the var locationName is still undefined (not set). Try it like this

function getLocationName(latitude, longitude, callback) {
    if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) {
        return false;
    }

    var locationName;
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude)

    // Reverse Geocoding using google maps api.
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                locationName = results[1].formatted_address;
                alert(locationName);
            }
            else {
                locationName = "Unknown";
            }
        }
        else {
            locationName = "Couldn't find location. Error code: " + status;
        }
        alert(locationName);
        callback(locationName);
    });
}

To get the "return" you have to create a your own callback. Try like this

$("#id").on("event", function (event, ui) {
    getLocationName(latitude, longitude, function(result){
        $("#userLocation").text(result);
    });
});

As for the alert, the return is called before the ajax request. So you have to use a callback to be called when the ajax request has done his job!

Lwyrn
  • 1,821
  • 1
  • 16
  • 27
  • Hi. Thanks for your answer. This sort of works. The alert 'alerts' the right value but the return doesn't return the right value to the function where I call getLocationName() from. Any thoughts? – reggaemahn Jul 28 '13 at 11:04
  • Thanks. Worked great. – reggaemahn Jul 28 '13 at 11:59
  • how can i assign result to a variable? i tried var x = getLocationName(latitude, longitude, function(result){ return result; }); alert (x); but this alerts undefined. any idea why? – AbtPst Feb 17 '16 at 22:35