简体   繁体   中英

javascript: getting the value of variables inside a callback function

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM