先看下最終的效果(默認可以獲得未來三天數據):

第一:首先准備條件(必須):
1.小程序已認證,有appID
2.必須把https://api.map.baidu.com 添加到小程序的合法域名列表中
上面兩個條件缺一不可,滿足后 繼續往下看
第二:在百度開放平台上創建一個應用,拿到Ak(前提有百度賬號)。申請地址:http://lbsyun.baidu.com/apiconsole/key

應用創建成果:

第三:萬事俱備,只欠東風,引入官方提供的JS文件(下載地址:http://lbsyun.baidu.com/index.php?title=wxjsapi/wxjs-download),該文件中已經寫好了請求數據的代碼,我們只需要將數據取出來就好了
例如:
// 引用官方文件 var map = require('../../bmap-wx.min.js'); Page({ data:{ ak:"你的AK", // 用於保存當日天氣信息 TayData:'', // 用於保存未來天氣信息 futureWeather:[] }, onLoad:function(options){ var that = this; // 新建bmap對象 var BMap = new bmap.BMapWX({ ak: that.data.ak }); 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({ TayData: weatherData, futureWeather: futureWeather }); } // 發起weather請求 BMap.weather({ fail: fail, success: success }); } })
自己手動請求數據:
Page({ data: { // 用於保存當日天氣數據 Tad_weather: [], // 用於保存未來天氣數據 future_weather: [] }, /** * 生命周期函數--監聽頁面初次渲染完成 */ onReady: function () { var that = 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); that.setData({ Tad_weather: res.data.results[0].index future_weather: res.data.results[0].weather_data }) } }) } })
