我正在从教程中开发 node.js 命令行天气应用程序,我意识到当我输入一个字符串作为输入时,只取第一个单词,字符串被拆分成一个单词数组,并且只返回第一个单词
应用程序.js
const yargs = require('yargs');
const geocode = require('./geocode/geocode.js');
const argv = yargs
.options({
a: {
demand: true,//this argument is require
alias: 'address',
describe: 'Address to fetch weather for',
string: true//always parse the address argument as a string
}
})
.help()
.alias('help', 'h')
.argv;
geocode.geocodeAddress(argv.address, (errorMessage, results) => {
if(errorMessage){
console.log(errorMessage);
}else{
console.log(JSON.stringify(results, undefined, 4));
}
});
地理编码.js
const request = require('request');
let geocodeAddress = (address, callback)=>{
let encodedAddress = encodeURIComponent(address);
request({
url:`https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json:true
}, (err, response, body)=>{
if(err){
callback('unable to connect to service');
}else if(body.status === 'ZERO_RESULTS'){
callback('unable to find address');
}else if(body.status === 'OK'){
callback(undefined, {
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
});
}
});
}
module.exports.geocodeAddress = geocodeAddress;