微信小程序调用天气信息
wx.request({ url: example.php, //仅为示例,并非真实的接口地址 data: { x: , y: }, header: { content-type: application/json // 默认值 }, success (res) { console.log(res.data) } })
以和风天气为例 它可以通过开发文档查看调用很多信息基本上只用前几个就可以了,但是现在也很复杂需要申请好多数据,没有之前的方便。 在这里插入代码片
首先需要创建和风天气账号,并创建应用管理获取KEY,这是之后调用函数API要用到的一个参数
这是和风天气提供的示例,只需要酱下面的网址填入到你的url中就可以了,其中坐标要使用申请得到的经纬度参数,KEY也要自己注册账号申请
// 这是和风天气提供的示例,只需要酱下面的网址填入到你的url中就可以了,其中坐标要使用申请得到的经纬度参数,KEY也要自己注册账号申请 // 商业版 https://api.qweather.com/v7/weather/now?location=101010100&key=你的KEY // 开发版 https://devapi.qweather.com/v7/weather/now?location=101010100&key=你的KEY { "code": "200", "updateTime": "2020-06-30T22:00+08:00", "fxLink": "http://hfx.link/2ax1", "now": { "obsTime": "2020-06-30T21:40+08:00", "temp": "24", "feelsLike": "26", "icon": "101", "text": "多云", "wind360": "123", "windDir": "东南风", "windScale": "1", "windSpeed": "3", "humidity": "72", "precip": "0.0", "pressure": "1003", "vis": "16", "cloud": "10", "dew": "21" }, "refer": { "sources": [ "QWeather", "NMC", "ECMWF" ], "license": [ "commercial license" ] } }
调用获取地理位置函数wx.getLocation(Object object),他其中还有很多功能不过我们只需要使用其中的经纬度(latitude,longitude)就可以了
wx.getLocation({ type: wgs84, success (res) { const latitude = res.latitude const longitude = res.longitude const speed = res.speed const accuracy = res.accuracy } })
需要在/src/utils/app.json申请地理位置使用权限,添加下列代码即可
"permission":{ "scope.userLocation":{ "desc": "你的位置信息将用于天气效果展示" } },
下面的程序就是你根据自己的需求使用和风天气提供的API函数
wx.getLocation({ type: "wgs84", success(res){ const latitude = res.latitude; const longitude = res.longitude; const key = "your key"; wx.request({ url: `https://free-api.heweather.net/s6/weather/now?location=${longitude},${latitude}&key=${key}`, //获取天气数据接口的API地址 success (res) { // console.log(res.data); const { basic , now} = res.data.HeWeather6[0]; // console.log(basic); // console.log(now); that.area = basic.location; that.city = basic.parent_city; that.weather = now.cond_txt; wx.request({ url: `https://free-api.heweather.net/s6/air/now?location=${that.city}&key=${key}`, //获取天气数据接口的API地址 success (res) { // console.log(res.data); const { air_now_city} = res.data.HeWeather6[0]; const { aqi, qlty} = air_now_city; that.airText = qlty that.airValue = aqi } }); wx.request({ url: `https://devapi.qweather.com/v7/indices/1d?type=1&location=${longitude},${latitude}&key=${key}`, //获取天气数据接口的API地址 success (res) { //console.log(res.data); const { category, text} = res.data.daily[0]; // console.log(daily); that.weather = category that.weatherAdvice = text // console.log(category); // console.log(text); } }); } }); } });
我获取了,地理位置,天气信息,出行运动建议和指数。效果如下
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信小程序-- button按钮详解