读书时,发现书上的和风天气接口有些过时了,
于是按着视频中周老师教的方法,修改了一些代码。
而且还要加一个函数,才可以获取到天气数据,之前书上说的地区名是拼音,但现在是数字,
最后想了想,又看了两遍视频,终于明白如何修改了。
并且还加了三天的实时天气信息,本来想加24小时的天气信息,但苦于有权限,无法增加。
代码中加粗文字就是修改和增加的
【index.js】
data: {
region:['北京市','北京市','朝阳区'],
locationid:'101010100',
threeday:[],
now:{
temp:0,
text:'未知',
icon:'999',
humidity:0,
pressure:0,
vis:0,
windDir:0,
windSpeed:0,
windScale:0
}
},
regionChange: function (e) {
// console.log(e);
this.setData({
region:e.detail.value
})
this.getLocationid();
},
// 获取城市id
getLocationid:function(){
var that = this;
wx.request({
url: 'https://geoapi.qweather.com/v2/city/lookup',
data:{
location:that.data.region[2],
adm1: that.data.region[1],
key:'和风天气密钥'
},
success:function(res_id){
// console.log(res_city.data.location[0].id);
that.setData({
locationid:res_id.data.location[0].id
})
}
})
this.getWeather();
this.getthreeday();
},
// 获取天气数据
getWeather: function () {
var that = this;
wx.request({
url: 'https://devapi.qweather.com/v7/weather/now',
data:{
location:that.data.locationid,
key:'和风天气密钥'
},
success:function(res){
// console.log(res.data);
that.setData({
now:res.data.now
})
}
})
},
// 获取3天天气
getthreeday:function(){
var that = this;
wx.request({
url: 'https://devapi.qweather.com/v7/weather/3d',
data:{
location:that.data.locationid,
key:'和风天气密钥'
},
success:function(res){
// console.log(res.data.daily)
that.setData({
threeday:res.data.daily
})
}
})
},
onLoad: function (options) { this.getLocationid() },
【index.xwml】
<div class="container">
<!--地区-->
<picker mode="region" bindchange="regionChange">
<view>{{region}}</view>
</picker>
<!--天气信息-->
<text>{{now.temp}}℃ {{now.text}}</text>
<!--天气图标
<image src="/images/weather_icon/{{now.icon}}.png" mode="widthFix"></image>-->
<!--3日内信息-->
<view class="detail detail2">
<block class="detail_box" wx:for="{{threeday}}" wx:key="threeday_{{index}}">
<view class="bar">
<view class="box">{{item.fxDate}}</view>
<view class="box"><image src="/images/weather_icon/{{item.iconDay}}.png" mode="widthFix"></image></view>
<view class="box">{{item.tempMax}}</view>
<view class="box">{{item.tempMin}}</view>
</view>
</block>
</view>
<!--天气信息-->
<view class="detail">
<view class="bar">
<view class="box">温度</view>
<view class="box">气压</view>
<view class="box">能见度</view>
</view>
<view class="bar">
<view class="box">{{now.humidity}} %</view>
<view class="box">{{now.pressure}} hpa</view>
<view class="box">{{now.vis}} km</view>
</view>
<view class="bar">
<view class="box">风向</view>
<view class="box">风速</view>
<view class="box">风力</view>
</view>
<view class="bar">
<view class="box">{{now.windDir}}</view>
<view class="box">{{now.windSpeed}} km/h</view>
<view class="box">{{now.windScale}} 级</view>
</view>
</view>
</div>
css基本没变化,省略了。
网友评论