微信小程序 通过获取地理位置查看天气
1.在app.json中写入
"permission": { "scope.userLocation": { "desc": "你的位置信息将用于天气预报定位" } },
2.申请和风天气APIKEY
3.在js文件中设置变量
const APIKEY = "APIKEY"; //申请到的和风天气key
4.获取天气代码
//获取天气 getWeather() { var that = this wx.getLocation({ type: gcj02, success(res) { that.setData({ location: res.longitude + "," + res.latitude }) that.getCityByLoaction() that.weather() } }) },
5.根据坐标获取城市
getCityByLoaction() { var that = this wx.request({ url: https://geoapi.qweather.com/v2/city/lookupkey= + APIKEY + "&location=" + that.data.location, success(result) { var res = result.data if (res.code == "200") { var data = res.location[0] that.setData({ City: data.adm2, Province: data.adm1 }) } else { wx.showToast({ title: 获取城市信息失败, icon: none }) } } }) },
6.获取天气情况
weather() { var that = this wx.showLoading({ title: 加载中, }) wx.request({ url: https://devapi.qweather.com/v7/weather/nowkey= + APIKEY + "&location=" + that.data.location, success(result) { var res = result.data that.setData({ temp: res.now.temp, text: res.now.text, icon: res.now.icon }) } }) wx.hideLoading() }
结束啦。
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信小程序之订阅消息