微信小程序—调用API获取天气情况

1、在微信开发者工具中的.js文档参考wx.getLocation函数获取当前地理位置,注意在app.json文件中permission授权。

    "permission": {
    
    
      "scope.userLocation": {
    
    
        "desc": "你的位置信息将用于小程序位置接口的效果展示" 
      }
    },
        wx.getLocation({
    
    
        type: 'wgs84',
        success: function (res) {
    
    
            //console.log(res)
            var latitude = res.latitude
            var longitude = res.longitude

            that.getWeatherInfo(latitude, longitude);//天气情况
            that.getqweather(latitude, longitude);//空气质量
            that.getweatherAdvice(latitude, longitude);//天气建议
            that.getcity(latitude,longitude);//地理位置
            }
        })

2、以天气建议为例,参考和风天气参考文档,获得天气建议,注意key值去官方注册账号后申请(免费)

  getweatherAdvice: function (latitude, longitude){
    
    
    var _this = this;
    var type = 1;
    var key = '	自己申请';
    var url = 'https://devapi.qweather.com/v7/indices/1d?key='+key+'&location=' + longitude + ',' + latitude +'&type=' + type;
    wx.request({
    
    
      url: url, 
      success: function (res) {
    
    
        //console.log(res);
        var text = res.data.daily[0].text;
        _this.setData({
    
    
        text:text,
        })
      }
    })
  },

3、最后在.wxml文件中直接调用即可

            <view class="weater-advice">
              <label>{
    
    {
    
    text}}</label>  
            </view>

5、效果展示
在这里插入图片描述
5、引用
主要参考微信小程序官方文档、风天气开发文档,以及B站up画卿师兄

https://dev.qweather.com/
https://developers.weixin.qq.com/miniprogram/dev/framework/
https://www.bilibili.com/video/BV1di4y1F7sf?spm_id_from=333.337.search-card.all.click

猜你喜欢

转载自blog.csdn.net/weixin_42370166/article/details/125033896