Google Maps Api v3的地理代码地址,如何返回对象

Google Maps Api v3 geocode address, how to return the object

本文关键字:何返回 返回 对象 地址 v3 Api Maps 代码 Google      更新时间:2023-09-26

我试图通过google api v3地理编码功能返回地址的纬度和经度。地理编码工作得很好,我只是不能将结果设置为我的地理编码对象从函数返回。我怀疑这是一个作用域问题

function codeAddress(address) {
  var geocoder = new google.maps.Geocoder();
  //this is the container var which I will reurn
  var geocode={};
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
        geocode.success = true;
        geocode.position= results[0].geometry.location;
  //If I log geocode here I can see the position and success values in the object
  } else {
      geocode.success=false;
      geocode.message="Geocode was not successful for the following reason: " + status;
  }
});
  //If I log geocode here it's empty
  return geocode; 
}

感谢任何建议。

这绝对是一个作用域问题。传递给geocode请求的回调函数是异步执行的。

访问地理编码服务是异步的,因为Google地图API需要调用外部服务器。因此,你需要传递回调方法以在完成时执行请求。这个回调方法处理结果。

来源

这意味着您的codeAddress函数将始终返回一个空对象。