> 文章列表 > 微信小程序开发--利用和风天气API实现天气预报小程序

微信小程序开发--利用和风天气API实现天气预报小程序

微信小程序开发--利用和风天气API实现天气预报小程序

本来是参照《微信小程序开发实战》做一个天气预报小程序的,实际运行的时候提示错误,code 400,参数错误。说明问题应该出在查询API的语句上,没有返回结果。

查阅后才知道,可能书籍出版时间较早,现在的和风获取天气的API出现了一些调整,具体见实时天气 for API | 和风天气开发服务 官方文档

现在的参数location(必选)需要查询地区的LocationID或以英文逗号分隔的经度,纬度坐标(十进制,最多支持小数点后两位)。例如 location=101010100location=116.41,39.92

也就是 LocationID现在需要通过经度,纬度坐标服务获取:相当于在运行该语句前要先找到城市的LocationID,然后代入该语句就可以了

  • 这个是城市搜索API的请求语句

另外一点不同就是返回的天气数据now.具体变量名称也有变化,书上的now.hum,现在就是humidity,如果不修改,就会导致赋值错误。

 

具体代码:

// index.js

Page({

  data:{

    region:["江苏省","南京市",'玄武区'],

    locationid:101190108,

    now:{

      temp:0,

      text:'未知',

      icon:'999',

      humidity:0,

      pres:0,

      vis:0,

      windDir:0,

      windSpeed:0,

      windScale:0

    }

  },

//region变量在Data中定义了,是一个数组

  regionChange:function(e){

    this.setData({region:e.detail.value});

    this.getlocationid();

    this.getWeather();

  },

  getWeather:function(){

    var that=this;

    wx.request({

      url: 'https://devapi.qweather.com/v7/weather/now',

      data:{

        location:that.data.locationid,

        key:"你的key"

      },

      success:function(res){

        console.log(res.data) 

        that.setData({now:res.data.now})

      },

      fail:function(res){

        console.log('ERROR')

      }

      

    })

  },

  getlocationid:function(){

    var that =this;

    wx.request({

      url: 'https://geoapi.qweather.com/v2/city/lookup',

      data:{

        location:that.data.region[2],

        adm:that.data.region[1],

        key:"你的key"

      },

      success:function(res){

        console.log(res.data);

        that.data.locationid=res.data.location[0].id;

      }

    })

  },

      

  onLoad:function(options){

    this.getWeather();

  }

})