微信小程序获取实时天气

939 阅读1分钟

我用了高德开放平台提供的API

注册申请key

后面代码上会使用到这个key。 前往申请

微信图片_20211227103917.png

使用

  1. 在页面的 js 文件中,引入amap-wx.js 文件(amap-wx.js  从相关下载页面下载的 zip 文件解压后得到),
  2. 实例化 AMapWX 对象,并调用 getWeather 方法获取搜索数据,代码如下:
var amapFile = require('path/to/amap-wx.js'); //如:..­/..­/libs/amap-wx.js 

Page({ 
    onLoad: function() { 
        var that = this; 
        var myAmapFun = new amapFile.AMapWX({key:'高德Key'}); 
        myAmapFun.getWeather({ 
            success: function(data){ 
                //成功回调 
            }, 
            fail: function(info){ 
                //失败回调 console.log(info) 
            } 
        }) 
    } 
})

以上,我们可以获取到精确到区的天气;如果想获取市的天气我们可以使用getRegeo方法获取地理位置。

但是需要先获取位置的经纬度,可以使用wx.getLocation({})方法

wx.getLocation({
  type: 'gcj02', //返回可以用于wx.openLocation的经纬度
  success: function (res) {
    wx.hideLoading()
    let latitude = res.latitude //维度
    let longitude = res.longitude //经度
    // 获取详细地理位置
    myAmapFun.getRegeo({
      location: '' + longitude + ',' + latitude + '', // 经纬度
      success: function (data) {
        wx.hideLoading()
        that.setData({
          ['diary.city']: data[0].regeocodeData.addressComponent.city
        })
      },
      fail: function (info) {}
    })
     // 获取天气
    myAmapFun.getWeather({
      success: function (data) {
        wx.hideLoading()
        that.setData({
          ['diary.weather']: data.weather.data,
          ['diary.temperature']: data.liveData.temperature
        })
      },
      fail: function (info) {}
    })
  }
})

配置服务器域名

前往小程序开发管理处设置合法域名

微信图片_20211227103622.png

到此,我们就完成了在小程序上查询天气。