小程序引入百度api天气预报

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

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

 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
        })
      }
    })
  }
})
复制代码

 

posted @   .NET_海  阅读(3307)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示