这是我正在使用的: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
的索引0
,res
是一个对象。现在您的回调使用已修复,这是唯一剩下的问题,除了
-
cleanedaddress
没有定义,但我只是想当然地认为它必须在代码中的更高位置。 -
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 }
希望这有帮助。