以下步骤为在和风天气官网创建好账号并获取到key后(和风天气官网开发文档):https://dev.qweather.com/docs/start/):
获取天气信息
onShow: function () {
this.getLocation();//如果需要获取当前位置
或
this.getWeatherInfo(29.950461, 120.309056);//如果只获取一个地方的天气
},
getLocation:function(){
var that = this;
wx.getLocation({
type: 'wgs84',
success: function (res) {
var latitude = res.latitude
var longitude = res.longitude
that.getWeatherInfo(latitude, longitude);
}
})
},
获取天气方法(天气预报其中也包括了当天的实时天气)
/**
* 天气
*/
getWeatherInfo: function (latitude, longitude){
var _this = this;
var key = '57d69cf259584bd080b7f6b16b122***';//你自己的key
//需要在微信公众号的设置-开发设置中配置服务器域名
// url='https://devapi.qweather.com/v7/weather/now?location=101010100&key=你的KEY' // 当天实况天气
var url = 'https://free-api.heweather.com/s6/weather?key='+key+'&location=' + longitude + ',' + latitude;
wx.request({
url: url,
data: {},
method: 'GET',
success: function (res) {
console.log(res);
var daily_forecast_today = res.data.HeWeather6[0].now;//今天天气
_this.setData({
today: daily_forecast_today,
todyIcon: '../../pic/weather/' + daily_forecast_today.cond_code+'.png', //在和风天气中下载天气的icon图标,根据cond_code_d显示相应的图标
});
}
})
}
页面展示
<view class="weather-box">
<image src="{{todyIcon}}" class="weather-icon"></image>
<view class="weather-info">
<view class="view1">{{today.cond_txt}}</view>
<view class="view2">{{today.tmp}}℃</view>
</view>
</view>
展示效果
天气图标在GitHub上获取:https://dev.qweather.com/docs/start/icons/
参考文档: https://zhuanlan.zhihu.com/p/33596283