节点谷歌地理编码器回调不起作用



这是我正在使用的:getLocation('123 Foobar Ln');

function getLocation(location) {
  console.log(location); // prints 123 Foobar Ln
  getLocationData(location, function(gotLocation) {
    console.log('hello?'); // this doesn't print
    return gotLocation;
  });
}
function getLocationData(location, callback) {
  geocoder.geocode(location, function(err, res) {
    if (res[0] != undefined) {
      geoaddress = (res[0].formattedAddress);
      addressmessage = 'Formatted Address: ' + geoaddress;
      callback(addressmessage);
    } else {
      geocoder.geocode(cleanedAddress, function(err, res) {
        addressmessage = 'null';
        if (res[0] != undefined) {
          geoaddress = (res[0].formattedAddress);
          addressmessage = 'Formatted Address: ' + geoaddress;
          callback(addressmessage);
        } else {
          addressmessage = 'Address could not be found: ' + location;
          callback(addressmessage);
        }
      });
    }
  });
}

我正在努力让getLocation对getLocationData的回调做任何事情。

当我运行以下内容时,我得到的唯一输出是:123 Foobar Ln

有人可以指出我在这里做错了什么吗?

这里最让你绊倒的错误可能是你正在搜索res的索引0res是一个对象。现在您的回调使用已修复,这是唯一剩下的问题,除了

  1. cleanedaddress没有定义,但我只是想当然地认为它必须在代码中的更高位置。
  2. 123 Foobar Lane是一个可能不存在的地址,但也许你只是在帖子中使用它。

简化的工作版本:

var geocoder = require('google-geocoding');
//https://www.npmjs.com/package/google-geocoding
function getLocation(location) {
  getLocationData(location, function(latLong) {
    console.log('latLong:', latLong);
  });
}
function getLocationData(location, callback) {
  geocoder.geocode(location, function(err, res) {
    if (err){
      console.log('geocode error', err);
    }else{
      callback(res);
    }
  });
}
getLocation('1060 W Addison St, Chicago, IL 60613');
// => latLong: { lat: 41.9474536, lng: -87.6561341 }

希望这有帮助。

最新更新