很久没写文章了o(╥﹏╥)o,今天趁着不是太忙,教大家一个在项目中添加天气预报信息的一个方法,介于网上的组件vue-weather-mini的作者对请求次数有这极大地限制,还没正式开始联调呢,就被告知超过最大请求次数,也是很无奈。。。。所以我们自己找来了一些api来简单实现一下
准备工作:
1:需要一个获取天气的API接口
开发文档地址:https://www.qweather.com/weather/huangpu-101020400.html
https://devapi.qweather.com/v7/weather/now?location= l o n g i t u d e , {longitude}, longitude,{latitude}&key=自己去创建一个key
2:需要一个api去获取地理位置信息,然后补充到天气接口中的请求参数当中
https://ipapi.co/json/—这个是地理位置请求接口
https://ipapi.co—大家可以去这个网站去看接口文档
开始操作步骤:
1:发起获取位置信息请求
// 定位信息
const locationInfoObj = ref({
});
const getLocation = () => {
const localInfo = localStorage.getItem("locationInfo");
if (!localInfo) {
axios({
url: "https://ipapi.co/json/",
method: "get",
timeout: 20000
}).then(res => {
if (res.status == 200) {
locationInfoObj.value = res.data;
// 如果本地没有缓存位置信息,再缓存一下
localStorage.setItem("locationInfo", JSON.stringify(res.data));
// 调用天气查询
getWeather(res.data, locationInfoObj.value.city == res.data.city);
}
});
} else {
const tempLocalInfo = JSON.parse(localInfo);
getWeather(tempLocalInfo, locationInfoObj.value.city == tempLocalInfo.city);
}
};
这里呢我给出了返回结果和字段描述,觉得不懂的可以自己去文档里面看也行
2:在拿到位置信息后,我们就可以根据位置信息去获取当地天气了
开发文档地址:https://www.qweather.com/weather/huangpu-101020400.html
const getWeather = (v, f) => {
const weatherInfo = JSON.parse(localStorage.getItem("weatherInfo")) || {
};
const period = new Date().getTime() - new Date(weatherInfo.obsTime).getTime();
if (f && period <= 1000 * 60 * 60) {
weatherInfoObj.value = weatherInfo;
} else {
axios({
url: `https://devapi.qweather.com/v7/weather/now?location=${
v.longitude},${
v.latitude}&key=这里去自己申请一个key,我就不把我的贴出来了`,
method: "get"
}).then(res => {
if (res.status == 200) {
weatherInfoObj.value = res.data.now;
localStorage.setItem("weatherInfo", JSON.stringify(res.data.now));
}
});
}
};
请求的结果如下,返回字段里面字段的含义,我就不做介绍了,大家可以去文档里面自己去了解一下
3:我们根据已有的天气信息来达到自己的目的,接下来看我用已有信息展示的效果
到这里就结束啦,再见再见