Return 来自 Jquery 函数的数据

Return data from Jquery Function

我正在尝试从地理反向编码和 return 实际调用者中获取地址组件。但即使地址正确,returned 值也始终未定义。这就是我试图获取地址的方式。

var geocoder;
var addresss = codeLatLng(23.750875259244058, 56822900823215);
alert(address);

//Getting the address through reverse geo coding
var address;

function codeLatLng(lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);

    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results)
            if (results[1]) {
                //formatted address
                alert(results[0].formatted_address)

                //find country name
                for (var i = 0; i < results[0].address_components.length; i++) {
                    for (var b = 0; b < results[0].address_components[i].types.length; b++) {

                        //there are different types that might hold a city    
                        admin_area_lvl_1 usually does in come cases looking
                        for sublocality type will
                        be more appropriate
                        if (results[0].address_components[i].types[b] ==
                            "administrative_area_level_1") {
                            //this is the object you are looking for
                            city = results[0].address_components[i];
                            break;
                        }
                    }
                }
                //city data
                alert(city.short_name + " " + city.long_name)
                address = city.short_name;

            } else {
                alert("No results found");
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
    return address;
}

您必须使用 jQuery.Deferred(),因为这是一个异步函数。

 var geocoder;
 var addresss = codeLatLng(this.getPosition().lat(),      
 this.getPosition().lng());

 // now your addresss wariable is a promise you can access it like this

addresss.done(function(data){
    //data is your resolved addres
    //do your staff here
    //Getting the address through reverse geo coding
    var address = data;
})


function codeLatLng(lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);

    //define jquery deffered
    var promise= new jQuery.Deferred();

    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results)
            if (results[1]) {
                //formatted address
                console.log(results[0].formatted_address)

                //find country name
                for (var i = 0; i < results[0].address_components.length; i++) {
                    for (var b = 0; b < 
 results[0].address_components[i].types.length; b++) {

                        //there are different types that might hold a city    
   admin_area_lvl_1 usually does in come cases looking for sublocality type will 
   be more appropriate
                        if (results[0].address_components[i].types[b] == 
    "administrative_area_level_1") {
                            //this is the object you are looking for
                            city = results[0].address_components[i];
                            break;
                        }
                    }
                }
                //city data
                console.log(city.short_name + " " + city.long_name)
                 promise.resolve( city.short_name);

            } else {
                console.log("No results found");
            }
        } else {
            console.log("Geocoder failed due to: " + status);
        }
    });
    return promise;

}

选项 2 你可以使用下面的回调函数

 var geocoder;
 var addresss = 
 codeLatLng(this.getPosition().lat(), this.getPosition().lng(), function(address){
    //do your staff here
    //Getting the address through reverse geo coding
 });


function codeLatLng(lat, lng, callback) {
    var latlng = new google.maps.LatLng(lat, lng);

    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results)
            if (results[1]) {
                //formatted address
                console.log(results[0].formatted_address)

                //find country name
                for (var i = 0; i < results[0].address_components.length; i++) {
                    for (var b = 0; b < 
 results[0].address_components[i].types.length; b++) {

                        //there are different types that might hold a city    
   admin_area_lvl_1 usually does in come cases looking for sublocality type will 
   be more appropriate
                        if (results[0].address_components[i].types[b] == 
    "administrative_area_level_1") {
                            //this is the object you are looking for
                            city = results[0].address_components[i];
                            break;
                        }
                    }
                }
                //city data
                console.log(city.short_name + " " + city.long_name)
                //callback your address here
                callback( city.short_name);

            } else {
                console.log("No results found");
            }
        } else {
            console.log("Geocoder failed due to: " + status);
        }
    });
    callback(false);

}

geocoder.geocode() 函数是异步的,在收到 Google 的响应后 运行 有一个回调函数。但在您的情况下,return address; 语句在回调函数之外,因此 codeLatLang(lat,lng) return 是在完全接收响应之前和地址变量被赋值之前的地址。

将您的 return address 语句移动到回调函数中可以解决这个问题。

(确保 return 在响应失败的情况下使用适当的错误值。)