简单进行记录一下,如何通过定位来获取经纬度,在通过高德开放的API来进行天气预报数据的获取
背景:
本来我们为合作方公司设计了一款可用的app,原本的app上本来功能好好的,功能不能说很完善吧,但是对于客户进行日常的工作还是没啥问题的。但是唯一的缺点就是,上个离职的前辈估计为了赶进度还是敷衍了事,于是对于页面进行简单的”大刀阔斧“,好家伙,页面直接黑白配。完美。但是客户看见了不乐意啊,就一直催促着我们进行整改,于是只能带锅上阵了,一顿画原型图咔咔造,最终还算能看了(虽然也很丑),先上效果图。
但是客户想添加一个通过定位获取当前城市的天气功能。那我们简单理清下思路
一、
通过使用uni.getLocation()这个API进行授权获取相应的定位信息,在通过定位获取高德的开放API接口调取天气信息数据。
注意:这里说明,高德需要的的请求参数是城市名称,不是经纬度,小伙伴们注意,
至于怎么生成key,可以查看官方文档
高德网址链接:天气查询-API文档-开发指南-Web服务 API | 高德地图API
二、获取城市经纬度并通过转换成所在城市
getSetting(){ uni.getLocation({ type:'wgs84', success:(res)=>{ const latitude = res.latitude; const longitude = res.longitude; console.log('经度'+longitude,'纬度'+latitude) // const latitude = 22.8092997; const longitude = 113.547439; // 将经纬度转换为城市名称 uni.request({ url:'https://restapi.amap.com/v3/geocode/regeo', data: { key: 'your-key',//自己的高德密钥key location: `${longitude},${latitude}` }, success:(res)=>{ const city = res.data.regeocode.addressComponent.city; this.cityName = city }, fail:(error)=>{ console.error('获取城市名称失败:', error); } }); }, fail:(error)=>{ console.error('获取地理位置失败:', error); } }); },
三、根据转换后的城市调取高德API的天气接口
// 获取天气预报 uni.request({ url: 'https://restapi.amap.com/v3/weather/weatherInfo', data: { city: city, key: 'your-key'//自己的高德密钥key }, success:(res)=>{ const weatherData = res.data.lives; console.log('当前城市:', city); console.log('天气信息:', weatherData[0]); this.temperature =weatherData[0].temperature this.humidity = weatherData[0].humidity this.weather = weatherData[0].weather this.winddirection = weatherData[0].winddirection this.windpower = weatherData[0].windpower console.log(this.temperature) }, fail:(error)=>{ console.error('获取天气信息失败:', error); } });
结果:
接下来奉献完整代码
getSetting(){ uni.getLocation({ type:'wgs84', success:(res)=>{ const latitude = res.latitude; const longitude = res.longitude; console.log('经度'+longitude,'纬度'+latitude) // const latitude = 22.8092997; const longitude = 113.547439; // 将经纬度转换为城市名称 uni.request({ url:'https://restapi.amap.com/v3/geocode/regeo', data: { key: 'your-key',//自己的高德密钥key location: `${longitude},${latitude}` }, success:(res)=>{ const city = res.data.regeocode.addressComponent.city; this.cityName = city // 获取天气预报 uni.request({ url: 'https://restapi.amap.com/v3/weather/weatherInfo', data: { city: city, key: 'your-key'//自己的高德密钥key }, success:(res)=>{ const weatherData = res.data.lives; console.log('当前城市:', city); console.log('天气信息:', weatherData[0]); this.temperature =weatherData[0].temperature this.humidity = weatherData[0].humidity this.weather = weatherData[0].weather this.winddirection = weatherData[0].winddirection this.windpower = weatherData[0].windpower console.log(this.temperature) }, fail:(error)=>{ console.error('获取天气信息失败:', error); } }); }, fail:(error)=>{ console.error('获取城市名称失败:', error); } }); }, fail:(error)=>{ console.error('获取地理位置失败:', error); } }); },