【问题标题】:Google Maps API v3, Geolocation not returning correctlyGoogle Maps API v3,地理位置未正确返回
【发布时间】:2013-04-13 21:21:48
【问题描述】:

我有一个问题,如果我将地理编码的结果放入一个变量中,该变量返回空。这是我的代码:

地图初始化:

function init_map() {
  geocoder = new google.maps.Geocoder();

  var center_address = get_long_lat("Salisbury, UK");
  var latlng = new google.maps.LatLng(center_address);

  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById("gmap"), mapOptions);
}

如您所见,我正在尝试通过使用自定义函数 get_long_lat 将地址转换为 Long 和 Lat 来将地图中心定位到我的家乡:

获得长距离和纬度

function get_long_lat(address) {

      var result = "";

      geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              result = results[0].geometry.location;
          } else {
            result = "Unable to find address: " + status;
          }
      });

      return result;
  }

现在,结果作为空字符串返回。但是,如果我要显示 results[0].geometry.location 的警报,它会显示我期望的正确值吗?

为什么它不想返回这个值?

【问题讨论】:

标签: javascript google-maps google-maps-api-3


【解决方案1】:

地理编码器是异步的。您不能从异步函数返回结果。您应该在回调中使用 result 值。

更具体地说,您的 return result; 行实际上是在分配 result 变量之前执行的。

【讨论】:

  • 对不起,我是一个完整的 JS 菜鸟,在回调中使用结果值是什么意思?你有我可以看的小代码示例吗>
  • 您传递给地理编码器的匿名函数,接受参数resultsstatus 的函数?那是一个回调函数。使用该回调函数中的 result 值做任何你想做的事情。
【解决方案2】:
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {});

这段代码调用 Google 服务器以检索地理编码信息。在收到来自 Google 服务器的响应后,它会执行指定的回调函数。

return result;

此行在回调函数检索到信息之前被命中,因此结果仍然为空。检索到信息后,将调用回调函数并填充结果。但为时已晚,“get_long_lat”函数已经返回了它的结果,返回的时候还是空的。

问题是返回结果的回调函数是异步运行的。

如果你这样写就行了:

function init_map() {
  geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': 'Salisbury, UK', 'region': 'uk' }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        var mapOptions = {
          zoom: 8,
          center: results[0].geometry.location,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        map = new google.maps.Map(document.getElementById("gmap"), mapOptions);

      } else {
        //Do whatever you want to do when the address isn't found.
        //result = "Unable to find address: " + status;
      }
  });

}

现在 mapOptions 仅在 Google 服务器返回响应后才被初始化。

【讨论】:

    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 2012-06-05
    • 2013-12-27
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多