Javascript 如何将变量从Google maps geocoder传递到另一个函数?

Javascript 如何将变量从Google maps geocoder传递到另一个函数?,javascript,Javascript,如何从传递给另一个函数的test2变量中获取值?我一直在尝试使用全局变量和链接函数,正如我在另一个线程中发现的那样,但无法让它们工作 function codeAddress(addresstocode) { var test2 = ['123','321']; geocoder.geocode( { 'address': addresstocode}, function(results, status) { if(status == google.maps.GeocoderSta

如何从传递给另一个函数的test2变量中获取值?我一直在尝试使用全局变量和链接函数,正如我在另一个线程中发现的那样,但无法让它们工作

function codeAddress(addresstocode) {

var test2 = ['123','321'];

geocoder.geocode( { 'address': addresstocode}, function(results, status) {

    if(status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);

        coded_lat = results[0].geometry.location.Ka;
        coded_long = results[0].geometry.location.La;

        //coded_location = [{"latitude" : coded_lat, "longitude" : coded_long}];

        //test2 = returnAddress(coded_location);

        test2 = [coded_lat,coded_long];

        //coded_lat = coded_location[0].latitude;
        //coded_long = coded_location[0].longitude;
        //returnAddress(coded_location);
    }

});

console.log('test2: '+test2);

return test2;


}

您必须创建一个函数来接收如下值:

function geocodeOK(lat, lng){
    // Do what you want with lat lng
}
在您的代码中:

function codeAddress(addresstocode) {

    var test2 = ['123', '321'];

    geocoder.geocode({
        'address': addresstocode
    }, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);

            coded_lat = results[0].geometry.location.Ka;
            coded_long = results[0].geometry.location.La;
            geocodeOK(coded_lat, coded_long);
        }

    });

}

您也不应该使用location.Ka,location.La的字母名称。“Ka”和“La”经常变化。使用location.lat()或location.lng()的适当函数。这样你的代码就不会突然中断