1. 程式人生 > >微信小程式(三)——引入百度api天氣資訊全過程

微信小程式(三)——引入百度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:

申請流程:

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了。

▍頁面渲染

既然資料已經獲取到了,那麼接下來就是頁面渲染了,在這一點上,智者見智,仁者見仁,大家可以各展所長,隨意發揮~~~

▍參考文件