使用谷歌地图:一个返回undefined的自定义javascript函数

Using Google Maps: a custom javascript function returning undefined

本文关键字:undefined 返回 自定义 函数 javascript 一个 谷歌地图      更新时间:2023-09-26

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

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时,它实际上仍然是undefined。内部函数稍后在异步操作(如果不是异步操作,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);
});