This question already has answers here:
Using a callback function with Google Geocode
                                
                                    (1个答案)
                                
                        
                        
                            Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                                去年关闭。
            
                    
我正在使用Google Map地理编码从地址获取纬度,经度值。这是我的代码,

var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
       console.log(place);
       var latd = results[0].geometry.location.lat();
       var lond = results[0].geometry.location.lng();
     }
    console.log(latd);
});
//console.log(latd);


在函数外部访问变量latd时,其值似乎为undefined。上面的代码有什么问题?

更新1:

    getlatlang(address);
    console.log(latd);//Not defined


function getlatlang(address)
{
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            //console.log(place);
            latd = results[0].geometry.location.lat();
            lond = results[0].geometry.location.lng();
             return latd,lond;
             }

     });
}

最佳答案

如果您想访问lat,则在函数外部很长的地方简单地分配它们而不在内部创建它们。您可以阅读有关JavaScript Scope的更多信息

    var latd;
    var lond;
     geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            console.log(place);
            latd = results[0].geometry.location.lat();
            lond = results[0].geometry.location.lng();
         }
      console.log(latd);
     });
     //console.log(latd);

09-13 01:53