【问题标题】:Why is this variable undefined or not returned?为什么这个变量未定义或未返回?
【发布时间】:2012-09-18 06:17:22
【问题描述】:

我有以下代码:

/*
 * converts a string to geolocation and returns it
 */

function stringToLatLng(string){
    if(typeof string == "string"){
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': string}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              console.log("LatLng: "+results[0].geometry.location);
              return results[0].geometry.location;
           } else {
              console.log("Geocode was not successful for the following reason: " + status);
           }
        });
   }
}

LatLng 将正确的位置打印到控制台,但是当我写这个时:

var pos = stringToLatLng('New York');
            console.log(pos);

我收到undefined 回复。这是为什么?谢谢

【问题讨论】:

  • 因为.geocode是异步的
  • 为什么在这种情况下意味着?我的意思是 LatLng 已正确打印到控制台......那我该如何修复它?我的意思是,我怎么能“等待”直到结果准备好?
  • 您无需等待 - 将所有适用于结果的代码放入回调中,就像您对 console.log 所做的那样

标签: javascript google-maps-api-3


【解决方案1】:

类似这样的:

function stringToLatLng(strloc, callback){
    if(typeof string == "string"){
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': strloc}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              callback.call({}, results[0].geometry.location);
           } else {
              console.log("Geocode was not successful for the following reason: " + status);
           }
        });
   }
}

stringToLatLng('New York', function(pos){
    console.log(pos);
});

在您的代码中,当您返回时,实际上是从 function(results, status){..} 函数返回,而不是 stringToLatLng 函数,正如 cmets 中所说的那样,它是一个异步调用,因此您必须使用回调.

【讨论】:

  • 我已经尝试了上面的 sn-p,它正在返回值,它显示在警报中,但是当我尝试将它分配给某个变量或在函数之外给出该警报时,它再次为空....任何帮助请...
  • 我收到一个空错误,在这种情况下会导致一些问题......
  • 这可能是因为您试图在 stringToLatLng('New York', function(pos){ console.log(pos); }); 之外使用变量方法,请确保您在警报之后直接使用它。
【解决方案2】:
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

参考: Javascript geocoding from address to latitude and longitude numbers not working

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2014-12-05
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多