使用GoogleMaps:返回未定义的自定义javascript函数

使用GoogleMaps:返回未定义的自定义javascript函数,javascript,Javascript,我试图从GetLocation返回变量coord,但它只返回未定义的变量。 感谢您的帮助 var coord = ""; function GetLocation(address) { var geocoder = new google.maps.Geocoder(); geocoder.geocode( { "address": address }, function (results, status) { if (status == google.map

我试图从GetLocation返回变量
coord
,但它只返回未定义的变量。 感谢您的帮助

var coord = "";
function GetLocation(address) {

    var geocoder = new google.maps.Geocoder();

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

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

            // This alert shows the proper coordinates 
            alert(coord);
        }
        else{ }

    });

    // this alert is undefined
    alert(coord);
    return coord;
}

function ParseLocation(location) {

    var lat = location.lat().toString().substr(0, 12);
    var lng = location.lng().toString().substr(0, 12);

    return lat+","+lng;
}

当您从外部函数返回
coords
时,实际上它仍然是
未定义的
。当异步操作(如果不是异步的,API通常只会将结果提供给您)完成后,内部函数将执行

尝试传递回调:

function GetLocation(address, cb) {

    var geocoder = new google.maps.Geocoder();

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

        if (status == google.maps.GeocoderStatus.OK) {
            cb(ParseLocation(results[0].geometry.location));
        }
        else{ }

    });
}
然后您可以这样使用它:

GetLocation( "asd", function(coord){
    alert(coord);
});

geocode()
是否异步执行?如果是这样的话,
coord
value在函数返回时还不知道。最终我想从函数返回值。然而,如果我这样做
var test=GetLocation(“asd”,function(coord){return coord;})我认为它不会工作,对吗?不,你不能这样做,这就是为什么它首先需要一个函数。如果你能这样做,他们会正常归还。嗯,对吗P如果您只是将javascript视为一个线性命令序列,那么您就无法使用javascript。事件、XHR请求等都是异步的。明白了,我只是希望有办法解决它。助教!