【问题标题】:Unable to access address from geocoder - reverse geocoding无法从地理编码器访问地址 - 反向地理编码
【发布时间】:2018-07-16 12:40:28
【问题描述】:

以下是我的 angular javascript 函数

getLocationName(latitude, longitude){
   var latlng = new google.maps.LatLng(latitude, longitude);
   var geocoder =  new google.maps.Geocoder();
   geocoder.geocode({ 'location': latlng }, (results, status) => {
     if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
           return results[1].formatted_address;  //prints value here but not outside the geocoder function
        }
     }
});
 }

location_name = this.getLocationName(lat, lng);

我将 location_name 设为未定义。我可以知道如何访问该地址。

【问题讨论】:

  • 你能附上结果(回复)吗?
  • @Zelda7 我已附上

标签: javascript angular google-maps google-maps-api-3 reverse-geocoding


【解决方案1】:

geocoder.geocode 接受一个回调函数,执行异步,然后在有结果时调用回调。

这意味着getLocationName在回调被调用之前返回,并且由于没有return语句它返回undefined

return results[1].formatted_address; 从回调中返回 formatted_address,而不是从 getLocationName

(results, status) => {
 if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
       return results[1].formatted_address;  //This returns from this callback
    }
 }
}

这可以通过(通常是邪恶的)setTimeout 伪造异步请求来证明:

function callMe(value) {
    setTimeout(function() { return value; }, 3000);

  return "This is not the value";
}

var result = callMe("This is the value");

console.log(result);

https://jsfiddle.net/cok3h4tn/1/

您可以看到“这不是值”正在打印,因为return "This is not the value"; 是返回值,而不是return value;

这里是google maps sample for geocoding,你可以看到它如何在回调中使用结果,而不是试图返回它。

或者,这是另一个如何使用回调的示例: 以此示例代码为起点。 它不起作用,但它是一个起点。

function callMe(value) {
    setTimeout(function() { return value; }, 3000);

    return "This is not the value";
}

var result = callMe("This is the value");

console.log(result);

callMe 被调用,然后我们想要获取结果,并对其进行处理。 我们可以用另一种方式写这个,我们想要对结果做的“某事”在它自己的函数handleResult中。

function handleResult(result) {
    console.log(result);
}

function callMe(value) {
    setTimeout(function() { return value; }, 3000);

    return "This is not the value";
}

var result = callMe("This is the value");

handleResult(result);

现在这仍然不正确,因为“错误”结果仍在传递给handleResult。 因此,我们需要进行更改,将“正确”结果传递给handleResult

function handleResult(result) {
    console.log(result);
}

function callMe(value) {
    setTimeout(function() { handleResult(value); }, 3000);

    return "This is not the value";
}

callMe("This is the value");

更新 jsfiddle:https://jsfiddle.net/cok3h4tn/4/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多