0
点赞
收藏
分享

微信扫一扫

微信小程序获取当前天气信息

上古神龙 2022-01-14 阅读 56

流程分为两步,首先获取当前位置经纬度,再请求第三方获取天气api

export function getLocation(that) { //that为引用此函数的页面传给此函数的页面this
  wx.getLocation({//用小程序官方api获取位置信息
    type: 'wgs84', // 获取位置信息必传参数
    success: (res) => { //成功之后的回调,开始请求天气api
      wx.request({
        //请求天气数据,通过经纬度
        url: 'https://devapi.qweather.com/v7/weather/now',
        data: {
          key: "************", //和彩云天气api使用的key,需要去和彩云获取
          location: `${res.longitude},${res.latitude}` //经纬度,模板字符串拼接
        },
        header: {
          'content-type': 'application/json'
        },
        //箭头函数为了修改this指向
        success: (res) => {
          console.log(res)
          that.setData({
            temp: res.data.now.temp, //气温
            weather: res.data.now.text, //天气状况
            weatherIcon: res.data.now.icon //图标
          })
          //return res.data.now.temp
        },
      })
    }
  })
};
举报

相关推荐

0 条评论