将回调函数与谷歌地理编码结合使用

Using a callback function with Google Geocode

本文关键字:编码 结合 回调 函数 谷歌      更新时间:2023-09-26

我已经为此苦苦挣扎了几个小时,即使在 Stack 上阅读了几个示例后,我也无法让它工作。 我是JS新手无济于事。

我正在尝试从 Google Geocoder API 检索有关地址的信息,然后将对象传递给另一个函数。 根据我的阅读,我知道我用来检索信息的函数是异步的,因此我需要使用回调函数来读取它。 但是,当我尝试执行此操作时,我的控制台仍然返回"未定义"。 我知道这些信息来自谷歌很好,因为当我在结果对象上使用 console.log() 时它会正确返回。

无论如何,这是我正在使用的:

function onSuccess(position) {
  getLocationData(position, function(locationData) {
    console.log(locationData);
  });   
}
function getLocationData(position, callback) {
  geocoder = new google.maps.Geocoder();
  var location = 'Billings,MT';
  if( geocoder ) {
    geocoder.geocode({ 'address': location }, function (results, status) {
      if( status == google.maps.GeocoderStatus.OK ) {
        return results[0];
      }
    });
  }
  callback();
}

就像我提到的,我得到的只是"未定义"。 如果我在getLocationData()返回值上方放置"console.log(results[0])",则返回的对象是正确的。 任何帮助将不胜感激。

您的问题是,您没有将回调连接到返回。由于geocode()函数本身已经是异步的,因此return在那里没有任何影响。相反,您必须将在此处返回的值直接传递给回调函数。喜欢这个:

function getLocationData(position, callback) {
  geocoder = new google.maps.Geocoder();
  var location = 'Billings,MT';
  if( geocoder ) {
    geocoder.geocode({ 'address': location }, function (results, status) {
      if( status == google.maps.GeocoderStatus.OK ) {
        callback(results[0]);
      }
    });
  }
}