怎么在nodejs中使用koa框架調(diào)用高德地圖接口?下面本篇文章給大家介紹一下node+koa調(diào)高德地圖接口的方法,希望對大家有所幫助!
高德開放平臺
調(diào)高德接口我們最重要需要什么❓ 需要高德地圖的key。按照如下的步驟進(jìn)入高德開放平臺。
創(chuàng)建應(yīng)用
添加key
這里注意一下不同的服務(wù)平臺,對應(yīng)不同的可使用服務(wù)。如下圖我是使用的是web服務(wù)
生成了key
koa請求第三方接口
koa2-request
在node中請求第三方接口,其實(shí)也就是發(fā)起一個request請求。爬蟲的原理也是如此。node發(fā)起請求的庫我們這里用到了koa2-request。因?yàn)槲覀冇玫搅薻oa框架。
-
地址: https://www.npmjs.com/package/koa2-request 其實(shí)也不用看了,介紹就這么多。
-
安裝:
npm install koa2-request
- 基本使用方法
這里支持async await
var koa2Req = require('koa2-request'); app.use(async(ctx, next) => { // request選項(xiàng) var res = await koa2Req('http://www.baidu.com'); ctx.body = res.body; });
開干
天氣接口
我們進(jìn)來后驚奇的發(fā)現(xiàn)他需要city和key作為參數(shù)
但是我們手動去輸入城市對應(yīng)的編碼不太現(xiàn)實(shí)。即使我記得住,它用戶體驗(yàn)也會極差。然后其實(shí)高德還有一個IP定位接口。那我們先跳到下面看一下。
IP定位
https://lbs.amap.com/api/webservice/guide/api/ipconfig
這里需要兩個參數(shù)ip和key
說到IP,那這里還需要一個插件
- 地址 https://www.npmjs.com/package/public-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' })();
如下是我的具體實(shí)現(xiàn),將ip和key作為參數(shù)
const koa2Req = require('koa2-request'); const publicIp = require('public-ip') // 獲取外網(wǎng)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將其轉(zhuǎn)為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') }
接下來就可以調(diào)用天氣接口了,天氣接口需要剛才我們獲得的城市編碼和key作為參數(shù)。
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; }