api接口用的和风天气
代码如下
// pages/weather/weather.js
Page({
/**
* 页面的初始数据
*/
data: {
apiKey: "1f5e75b8a3f0472aaf2f618268b30b4e",
City: '',
Country:'',
locationid:"",
latlongFlag: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
this.checkAuth()
},
checkAuth(){
// 将当前页面的 this 赋值给 vm, 以区别于下面回调函数中的 this
const that = this
wx.getSetting({
success(res) {
console.log(res)
// 1. scope.userLocation 为真, 代表用户已经授权
//第一次判断的时候scope.userLocation为undefined,需要运行一次wx.getLocation才可以设置位置允许
if ((typeof (res.authSetting['scope.userLocation']) == "undefined") ||
(res.authSetting['scope.userLocation'])) {
wx.getLocation({
type: 'wgs84',
success(res){
that.setData({
latitude: res.latitude,
longitude:res.longitude,
latlongFlag: true
})
console.log(res)
console.log(that.data.longitude,that.data.latitude)
that.getCityByLoaction()
}
})
}else {
// 2. 用户未授权的情况下, 打开授权界面, 引导用户授权.
that.requireLocation()
}
}
})
},
requireLocation(){
const that = this
wx.showModal({
title: '提示',
content: '需要获取您的位置信息,请前往设置界面开启位置权限。',
success: function (res) {
if (res.confirm) {
// 用户点击确定按钮,打开设置界面
wx.openSetting({
success: (settingRes) => {
console.log("settingRes",settingRes)
if (settingRes.authSetting['scope.userLocation']) {
// 用户已经同意授权
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 2000
});
that.checkAuth()
} else {
// 用户依然拒绝授权
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 2000
});
}
}
});
} else if (res.cancel) {
// 用户点击取消按钮
wx.showToast({
title: '您取消了授权',
icon: 'none',
duration: 2000
});
}
}
});
},
queryWeather(){
this.weather_now()
},
//通过经纬度获取城市的id
getCityByLoaction() {
var that = this
wx.request({
url: 'https://geoapi.qweather.com/v2/city/lookup?',
method: 'GET',
data: {
key: this.data.apiKey,
location: that.data.longitude.toString() + ',' + that.data.latitude.toString()
},
success: (res) => {
if(res.data.code === "200"){
this.setData({
locationid: res.data.location[0].id,
City:res.data.location[0].name,
Country:res.data.location[0].country
})
// Fetch weather information using locationid
this.getWeatherInfo(this.data.locationid);
}else{
console.log("fail to input city")
}
},
})
},
//通过输入城市名获取城市的id
weather_now(){
wx.request({
url: 'https://geoapi.qweather.com/v2/city/lookup?',
method: 'GET',
data: {
key: this.data.apiKey,
location: this.data.city
},
success: (res) => {
if(res.data.code === "200"){
this.setData({
locationid: res.data.location[0].id,
City:res.data.location[0].name,
Country:res.data.location[0].country
})
// Fetch weather information using locationid
this.getWeatherInfo(this.data.locationid);
}else{
console.log("fail to input city")
}
},
});
},
formatTime(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
const weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)
return {
hourly: [hour, minute].map(this.formatNumber).join(":"),
daily: [month, day].map(this.formatNumber).join("-"),
dailyToString: isToday ? "今天" : weekArray[date.getDay()]
}
},
formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
},
// 根据空气质量值返回对应的颜色类
getAqiCategory(value) {
// 根据实际情况定义不同的空气质量范围
if (value <= 50) {
return 'good';
} else if (value <= 100) {
return 'moderate';
} else if (value <= 150) {
return 'unhealthy';
} else {
return 'severe';
}
},
// 获取天气信息的方法
getWeatherInfo(locationid) {
const that = this
wx.request({
url: `https://devapi.qweather.com/v7/weather/now?location=${locationid}&key=${that.data.apiKey}`,
method: 'GET',
success: (res) => {
if(res.data.code === "200"){
that.setData({
now: res.data.now
})
}
// Handle the weather information response
console.log('Weather Now:', res.data);
},
fail: (error) => {
// Handle the request failure
console.error('Failed to fetch weather information:', error);
}
});
wx.request({
url: `https://devapi.qweather.com/v7/weather/24h?location=${locationid}&key=${that.data.apiKey}`,
method: 'GET',
success: (res) => {
if(res.data.code === "200"){
res.data.hourly.forEach(function(item){
item.time = that.formatTime(new Date(item.fxTime)).hourly
})
that.setData({
hourly: res.data.hourly
})
}
// Handle the weather information response
console.log('Weather 24 hour:', res.data);
},
fail: (error) => {
// Handle the request failure
console.error('Failed to fetch weather information:', error);
}
});
wx.request({
url: `https://devapi.qweather.com/v7/weather/7d?location=${locationid}&key=${that.data.apiKey}`,
method: 'GET',
success: (res) => {
if(res.data.code === "200"){
that.setData({
daily: res.data.daily
})
}
// Handle the weather information response
console.log('Weather 7d:', res.data);
},
fail: (error) => {
// Handle the request failure
console.error('Failed to fetch weather information:', error);
}
});
wx.request({
url: `https://devapi.qweather.com/airquality/v1/now/${locationid}?key=${that.data.apiKey}`,
method: 'GET',
success: (res) => {
console.log('Aqi Information:', res.data);
if(res.data.code === "200"){
that.setData({
aqiAvailable:true,
aqi: res.data.aqi[0],
aqicolor : this.getAqiCategory(res.data.aqi[0].value)
})
}else{
that.setData({
aqiAvailable:false
})
}
},
fail: (error) => {
// Handle the request failure
console.error('Failed to fetch aqi information:', error);
}
});
},
//获取输入框的值
getInutValue(e) {
console.log(e);
this.setData({
city: e.detail.value //获取页面input输入框输入的值,并传给city
})
console.log(this.data.city);
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
文章来源:https://www.toymoban.com/news/detail-825373.html
})文章来源地址https://www.toymoban.com/news/detail-825373.html
到了这里,关于微信小程序天气预报实战的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!