首页 > 技术文章 > 小程序引入百度api天气预报

bin521 2018-12-26 09:44 原文

先看下最终的效果(默认可以获得未来三天数据):

第一:首先准备条件(必须):

 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
        })
      }
    })
  }
})

 

推荐阅读