「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」
调高德接口我们最重要需要什么❓ 需要高德地图的key。按照如下的步骤进入高德开放平台。
这里注意一下不同的服务平台,对应不同的可使用服务。如下图我是使用的是web服务
在node中请求第三方接口,其实也就是发起一个request请求。爬虫的原理也是如此。node发起请求的库我们这里用到了koa2-request。因为我们用到了koa框架。
npm install koa2-request
var koa2Req = require('koa2-request');
app.use(async(ctx, next) => {
// request选项
var res = await koa2Req('http://www.baidu.com');
ctx.body = res.body;
});
我们进来后惊奇的发现他需要city和key作为参数
但是我们手动去输入城市对应的编码不太现实。即使我记得住,它用户体验也会极差。然后其实高德还有一个IP定位接口。那我们先跳到下面看一下。
这里需要两个参数ip和key
说到IP,那这里还需要一个插件
const publicIp = require('public-ip');
(async () => {
console.log(await publicIp.v4());
//=> '46.5.21.123'
console.log(await publicIp.v6());
//=> 'fe80::200:f8ff:fe21:67cf'
})();
如下是我的具体实现,将ip和key作为参数
const koa2Req = require('koa2-request');
const publicIp = require('public-ip') // 获取外网ip
const gaode_key = '8a674879652195a8bc6ff51357199517'
class clientController {
async getWeather(ctx, next) {
const ip_param = await publicIp.v4()
var res = await koa2Req(`https://restapi.amap.com/v3/ip?ip=${ip_param}&output=json&key=${gaode_key}`);
ctx.body = res;
}
}
返回值的格式
{
"status" :"1",
"info" :"OK",
"infocode" :"10000",
"province" :"北京市",
"city" :"北京市",
"adcode" :"110000",
"rectangle" :"116.0119343,39.66127144;116.7829835,40.2164962"
}
我们想要获得城市编码 adcode,res.body是我们从接口中取回的值。用JSON.parse将其转为JSON对象。
async getWeather(ctx, next) {
const ip_param = await publicIp.v4()
var res = await koa2Req(`https://restapi.amap.com/v3/ip?ip=${ip_param}&output=json&key=${gaode_key}`);
const city = JSON.parse(res.body).adcode
console.log(city,'city')
}
接下来就可以调用天气接口了,天气接口需要刚才我们获得的城市编码和key作为参数。
async getWeather(ctx, next) {
const ip_param = await publicIp.v4()
var res = await koa2Req(`https://restapi.amap.com/v3/ip?ip=${ip_param}&output=json&key=${gaode_key}`);
const city = JSON.parse(res.body).adcode
console.log(city,'city')
var res_weather = await koa2Req(`https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=${gaode_key}`)
let weather = {data: JSON.parse(res_weather.body)}
ctx.body = weather;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有