【问题标题】:how to use geocode() [duplicate]如何使用 geocode() [重复]
【发布时间】:2012-12-13 15:05:25
【问题描述】:

可能重复:
Reverse Geocode On Google Maps api v3

我想通过使用 lat-lang 值来查找地址,因为我正在使用新的 google.maps.Geocoder().geocode() 下面是方法的实现

function checkAddress(){
  var address="";
  var amstr = new google.maps.LatLng(37.556179,-122.288219);
  address = getAddress(amstr);
  alert(address);

}

function getAddress(latLng) {
    var geocoder = new google.maps.Geocoder();
        geocoder.geocode( {'latLng': latLng},
        function(results, status) {
         if(status == google.maps.GeocoderStatus.OK) {
          if(results[0]) {            
        return results[0].formatted_address;
          }
          else {
            return "No results";
          }
        }
        else {
          return "not working";
        }
      });
    }

但在运行上述代码后,我得到了“未定义”的结果。 请告诉我哪里做错了。

谢谢

【问题讨论】:

  • 欢迎来到 async 的精彩世界!你不能那样做。
  • 那么应该怎么做才能从 lat-lng 获取地址
  • 你能举个例子吗,因为我不知道该怎么做
  • @SLaks,他正在使用回调,(匿名函数内联),但它没有返回到他期望的位置。 ;-)

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


【解决方案1】:

geocoder.geocode() 是异步的。它只会在您的其余代码完成后的某个时间调用您的回调。

你需要在回调中返回值:

function getAddress(latLng, callback) {
    ...
    geocoder.geocode(..., function(...) {
        ...
        callback(someValue);
    });
}

【讨论】:

  • 现在我明白了!谢谢 SLaks 和马塞洛 !!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多