1

Im using google geocoder and I cant seem to find a way to set the value of the global variable inside the callback function

var status_temp;
var lat_temp;
var lng_temp;
var error_temp;
function set_status(status_input){
    status_temp=status_input;
}
function set_lat(lat_input){
    lat_temp=lat_input;
}
function set_lng(lng_input){
    lng_temp=lng_input;
}
function set_error(error_input){
    error_temp=error_input;
}
function geocode_address(address_input){
    var status_string;
    var error_message;
    var lat;
    var lng;
    geocoder.geocode( { 'address': address_input}, function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            set_status('found');
            set_lat(results[0].geometry.location.lat());
            set_lng(results[0].geometry.location.lng());
        } else {
            console.log("Geocode was not successful for the following reason: " + status);
            set_status('notfound');
            set_status(status);
        }
    });
    console.log(status_temp);
    if(status_temp==='found'){
        var data = ({
            status_string:status_temp,
            lat:lat_temp,
            lng:lng_temp,
        });
    }else{
        var data = ({
            status_string:status_temp,
            error_string:error_temp,
        });
    }
    return data;
}

I tried doing the normal way to set global variables which is declaring the variable outside the function, this latest one ive tried is using functions to set variables. what am i doing wrong?

taptipblard
  • 491
  • 1
  • 7
  • 15
  • I'd suggest you read this to learn about dealing with return values from async calls. This post is about ajax calls, but it's the exact same issue as you have here: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – jfriend00 Oct 13 '14 at 02:31
  • 1
    all you need to do is move the console call into the callback. bam, done. – dandavis Oct 13 '14 at 02:32
  • @dandavis - obviously, there's more of an objective here than just doing a `console.log()`. The OP has to learn how to handle async results either in the callback or by calling another function from the callback and passing the data to it. – jfriend00 Oct 13 '14 at 02:40
  • doing anything else to the data is just as simple as logging it. by producing something working, you realize (hopefully), "hey, i can just copy and paste the bottom half of my sync function into this callback!"... – dandavis Oct 13 '14 at 02:41

1 Answers1

2

You need to read about asynchronous javascript calls.
You are attempting to use the globals when they havent been set yet.
Your function cannot just return, it needs to use a callback to return the values, and the callback needs to be called from inside the geocode callback
note that your question title says "inside a callback" but you are not doing the console log from inside, its currently from outside.

Zig Mandel
  • 19,571
  • 5
  • 26
  • 36