JavaScript根据高德api获取相关信息

1. 根据高德api获取本地ip下的天气信息

步骤1. 依据高德api和发送的ip地址获取该ip所属的地址
步骤2. 将步骤1返回的地址码添加到高德获取天气的api中 查询天气信息

  //高德获取天气方法
let weatherInfo = new Promise((resolve, reject) => $.get("http://restapi.amap.com/v3/ip?key=高德KEY", (result) => !!result ? resolve(result) : reject('error')))
     .then(res => new Promise((resolve, reject) => $.get(`http://restapi.amap.com/v3/weather/weatherInfo?key=高德KEY=${res.adcode}`, (res) => !!res ? resolve(res) : reject('error'))))
     .then(res => !!res && !!res.lives && res.lives.length > 0 && res.lives[0])
     .catch(e => e);
weatherInfo.then(res => this.weatherInfo = res).catch(e => console.log(e));;

2.根据高德api获取给定地图范围内的poi

此处用到了async/await方法,并使用递归调用

const amapKey =高德KEY;
//poi API
const poiPolygonAPI = "http://restapi.amap.com/v3/place/polygon";
//此处的范围自己去定,按照格式写就好
const kgPolygon = "117.34560973,39.15703259|117.39951140,39.09652196|117.46482855,39.09343205|117.47572905,39.15935002|117.39487654,39.16999303|117.34560973,39.15703259";
/*
* 获取高德地图区域poi
* */
let page = 1;
let poiResult = [];
async function getPOI() {
  let res = await $.get(`${poiPolygonAPI}?key=${amapKey}&polygon=${kgPolygon}&offset=20&page=${page}&extensions=all`, res => res).catch(e=>console.error(e));
  poiResult.push(...res.pois);
  if (+res.count > page * 20) {
    page++;
     if (page > 100) {
        console.warn("已超过最大翻页数,请缩小查询范围,使页数小于100");
        return;
       }
    getPOI();//递归调用
  } else {
    console.log(poiResult);
    console.log(JSON.stringify(poiResult));
    return poiResult;
  }
}
getPOI();//执行

其中:高德KEY需要自己去申请 地址

和大家共勉,如有错误的地方,望请指正

你可能感兴趣的:(JavaScript根据高德api获取相关信息)