Mostafa Soufi
Mostafa Soufi

Reputation: 799

Return undefined value in javascript function

I have following code:

js load:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

js function:

<script type="text/javascript">

    var get_location;

    function get_google_latlng() {

        var geocoder =  new google.maps.Geocoder();
        geocoder.geocode( { 'address': 'iran'}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                window.get_location = results[0].geometry.location.lat();
            } else {
                window.get_location = status;
            }
        });

        return window.get_location;
    }

    var lat = get_google_latlng();

    alert(lat);
</script>

return Function is undefined

window.get_location command also does not work.

Upvotes: 1

Views: 3277

Answers (2)

Dipali Vasani
Dipali Vasani

Reputation: 2536

Try this code :

var get_location;
var geocoder =  new google.maps.Geocoder();
geocoder.geocode( { 'address': 'iran'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            get_location = results[0].geometry.location.d;
            alert(get_location);
        }
});

The problem with your code was, alert was getting executed first and then the get location function.

Upvotes: 0

Adrian Salazar
Adrian Salazar

Reputation: 5319

What you have is a problem with asynchronous functions. You don't have the values of the geocode method immediately, because you are making an ajax request and that takes time. Typical for a JavaScript newbie.

Callbacks and closures are the techniques that will make your life easier when programming JavaScript. I will suggest you to change your way of thinking, this ain't turbo-pascal anymore. This is JavaScript. async. Don't expect every function to immediately return results.

Example with callbacks:

// Ugly global variable
var get_location;

// Even more ugly global function
function get_google_latlng(callback) {

    var geocoder =  new google.maps.Geocoder();
    geocoder.geocode( { 'address': 'iran'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            window.get_location = results[0].geometry.location.lat();
        } else {
            window.get_location = status;
        }

        // Now you invoke the callback to notify that the results are ready
        callback();
    });

    // This is absolutely unnecessary
    return window.get_location;
}

get_google_latlng(function(){

   // Only here we are sure the variable was actually written       
   alert(window.get_location);
});

One last thing, never-ever-ever declare functions, and variables directly under "window", the global object in JavaScript, this is an anti pattern that will give you headaches in the future.

Please learn how to make anonymous functions.

Upvotes: 2

Related Questions