微信小程序(三)——引入百度api天气信息全过程

微信小程序本身是不提供天气api的,所以本文使用的是百度的api。

▍效果图

先附上个人制作的一个简易的效果图,为了排版方便,所以还有很多天气信息我没有放到页面上。

▍事先准备

如果想要达到预期效果,你的小程序必须满足以下条件:

1、必须有【APPID】,没有APPID的小程序无法申请到请求天气信息所必需的【百度AK】;

2、必须将【http://api.map.baidu.com】或【https://api.map.baidu.com】添加到微信小程序的【request 合法域名】中,否则数据请求将被阻止,那么我们还是获取不到天气信息。

▍申请百度AK

接口:

http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourak

接口说明:

根据经纬度/城市名查询天气的结果,本文将以根据【城市名】查询天气作为示例。

申请百度AK:

百度AK申请地址:百度地图开放平台

申请流程:

1、注册百度地图开放平台账号;

2、进入控制台;

3、选择【创建应用】;

4、填写小程序相关信息;

5、点击【提交】创建完成。

预期效果:

我们最终需要的就是这里的AK

▍请求天气数据信息

返回的JSON格式示例如下:

{
    "error": 0,
    "status": "success",
    "date": "2018-07-21",
    "results": [
        {
            "currentCity": "江夏",
            "pm25": "64",
            "index": [
                {
                    "des": "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
                    "tipt": "穿衣指数",
                    "title": "穿衣",
                    "zs": "炎热"
                },
                {
                    "des": "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。",
                    "tipt": "洗车指数",
                    "title": "洗车",
                    "zs": "较适宜"
                },
                {
                    "des": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。",
                    "tipt": "感冒指数",
                    "title": "感冒",
                    "zs": "少发"
                },
                {
                    "des": "天气较好,但炎热,请注意适当减少运动时间并降低运动强度,户外运动请注意防晒。",
                    "tipt": "运动指数",
                    "title": "运动",
                    "zs": "较不宜"
                },
                {
                    "des": "紫外线辐射强,建议涂擦SPF20左右、PA++的防晒护肤品。避免在10点至14点暴露于日光下。",
                    "tipt": "紫外线强度指数",
                    "title": "紫外线强度",
                    "zs": "强"
                }
            ],
            "weather_data": [
                {
                    "date": "周六 07月21日 (实时:35℃)",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
                    "weather": "晴转多云",
                    "wind": "东风微风",
                    "temperature": "37 ~ 28℃"
                },
                {
                    "date": "周日",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
                    "weather": "多云",
                    "wind": "北风3-4级",
                    "temperature": "35 ~ 27℃"
                },
                {
                    "date": "周一",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
                    "weather": "晴转多云",
                    "wind": "西北风微风",
                    "temperature": "36 ~ 28℃"
                },
                {
                    "date": "周二",
                    "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/xiaoyu.png",
                    "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
                    "weather": "小雨转多云",
                    "wind": "东风微风",
                    "temperature": "36 ~ 27℃"
                }
            ]
        }
    ]
}

提取数据方式有两种:

1、引入官方提供的JS文件:下载地址,该文件中已经写好了请求数据的代码,我们只需要将数据取出来就好了,示例代码如下:

// 引用百度地图微信小程序JSAPI模块
var bmap = require('../../libs/bmap-wx/bmap-wx.min.js');  
  
Page({  
  data:{  
    ak:"你的AK",  
    // 用于保存当日天气信息
    weatherData:'',
    // 用于保存未来天气信息
    futureWeather:[]  
  },  
  onLoad:function(options){  
    var that = this;  
    // 新建bmap对象   
    var BMap = new bmap.BMapWX({   
      ak: that.data.ak   
    });   
    var fail = function(data) {   
      console.log(data);  
    };   
    var success = function(data) {   
      console.log(data);  
              
      var weatherData = data.currentWeather[0];   
      var futureWeather = data.originalData.results[0].weather_data;  
      console.log(futureWeather);  
      weatherData = '城市:' + weatherData.currentCity + '\n' + 'PM2.5:' + weatherData.pm25 + '\n' +'日期:' + weatherData.date + '\n' + '温度:' + weatherData.temperature + '\n' +'天气:' + weatherData.weatherDesc + '\n' +'风力:' + weatherData.wind + '\n';   
      that.setData({   
        weatherData: weatherData,  
        futureWeather: futureWeather  
      });   
    }   
          
    // 发起weather请求   
    BMap.weather({   
      fail: fail,   
      success: success   
    });   
  }
})  

2、自己手动编写请求代码,示例代码如下:

Page({
  data: {
    // 用于保存当日天气数据
    weather: [],
    // 用于保存未来天气数据
    future: []
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var _this = this;
    wx.request({
      url: 'https://api.map.baidu.com/telematics/v3/weather?location=江夏&output=json&ak=你的AK',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res.data.results);
        _this.setData({
          weather: res.data.results[0].index
          future: res.data.results[0].weather_data
        })
      }
    })
  }
})

【注意】当我们通过wx.request请求网络数据成功后绑定数据时候可能会报错,错误代码示例如下:

Page({
  data: {
    // 用于保存当日天气数据
    weather: [],
    // 用于保存未来天气数据
    future: []
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.request({
      url: 'https://api.map.baidu.com/telematics/v3/weather?location=江夏&output=json&ak=你的AK',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res.data.results);
        this.setData({
          weather: res.data.results[0].index
          future: res.data.results[0].weather_data
        })
      }
    })
  }
})

报错是:

Cannot read property 'setData' of undefined

或者

this.setData is not a function

问题原因在于:这是因为this作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过this来setData。

【解决方案】所以我在wx.request执行之前,使用一个变量_this将this获取到了,然后在wx.request里操作_this,也就等同于在操作this了。

▍页面渲染

既然数据已经获取到了,那么接下来就是页面渲染了,在这一点上,智者见智,仁者见仁,大家可以各展所长,随意发挥~~~

▍参考文档

方倍工作室 | 百度天气预报接口CSDN | 微信小程序动态的加载数据懒人建站 | 微信小程序的ajax数据请求wx.request

猜你喜欢

转载自blog.csdn.net/i_dont_know_a/article/details/81141469