user1651804
user1651804

Reputation: 55

Why does this function call ruin the program and lead to undefined variables?

function getLatLng(address) {
    geocoder.geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert("Aus getLatLng: adresse:"+address+"Ergebnis: "+results[0].geometry.location);
            return results[0].geometry.location;
        } else {
            alert("Geocode was not successful for the following reason: "
                    + status);
        }
    });
}

I am using this javascript function in another function to get the Latitude/Longitude values from a string which is the address. The alert shows that the conversion is successfull but if i call the method i get a javascript error that it's still undefined.

    var start = document.getElementById("route_start").value;
    start = getLatLng(start);
    alert("Start: "+start);

What am i missing? The alert always shows an undefined variable. Why is that? I tried everything. Everything is going well til i call the function getLatLng. Something with the return isn't working. :(

Upvotes: 0

Views: 86

Answers (1)

codebox
codebox

Reputation: 20264

Your getLatLng function doesn't actually return anything, which is why start is undefined.

The return statement that you have written is contained within the anonymous function that gets passed to geocoder.geocode, so this won't actually get returned from your outer function.

Since geocoder.geocode is asynchronous you won't be able to write a getLatLng which returns the result in this way, instead you need to pass a callback function as an argument and invoke this function when the geocode API returns a value, something like:

function getLatLng(address, callback) {
    geocoder.geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(results[0].geometry.location);
        } else {
            alert("Geocode was not successful for the following reason: "
                    + status);
        }
    });
}

Upvotes: 2

Related Questions