js获取天气和当前定位的接口(免费版)
·
1、获取地址
const ipResponse = await axios.get("https://ipapi.co/json/");
2、获取天气
const city = ipResponse.data.city;
const { data } = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=899a6885afbf0702188ef94eb3204236&units=metric&lang=zh_cn`
);
3、获取日期
getCurrentTime() {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const dayOfWeek = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
][now.getDay()];
this.currentTime = `今天是${year}年${month}月${day}日,${dayOfWeek}`;
},
4、判断风向
getWindDirection(degrees) {
if (degrees >= 337.5 || degrees < 22.5) {
return "北风";
}
if (degrees >= 22.5 && degrees < 67.5) {
return "东北风";
}
if (degrees >= 67.5 && degrees < 112.5) {
return "东风";
}
if (degrees >= 112.5 && degrees < 157.5) {
return "东南风";
}
if (degrees >= 157.5 && degrees < 202.5) {
return "南风";
}
if (degrees >= 202.5 && degrees < 247.5) {
return "西南风";
}
if (degrees >= 247.5 && degrees < 292.5) {
return "西风";
}
if (degrees >= 292.5 && degrees < 337.5) {
return "西北风";
}
},
5、判断风速
getWindSpeed(speed) {
if (speed < 0.3) {
return "0级";
} else if (speed < 1.6) {
return "1级";
} else if (speed < 3.4) {
return "2级";
} else if (speed < 5.5) {
return "3级";
} else if (speed < 8.0) {
return "4级";
} else if (speed < 10.8) {
return "5级";
} else if (speed < 13.9) {
return "6级";
} else if (speed < 17.2) {
return "7级";
} else if (speed < 20.8) {
return "8级";
} else if (speed < 24.5) {
return "9级";
} else if (speed < 28.4) {
return "10级";
} else if (speed < 32.6) {
return "11级";
} else {
return "12级";
}
},
6、获取当日天气数据并展示
<div class="weather-box">
<div>{{ currentTime }}</div>
<div>
<span>{{ temperature }}℃</span>{{ weather }}
</div>
<div>{{ wind }}/湿度{{ humidity }}%</div>
<img :src="weatherImage" alt="" />
</div>
async getWeatherData() {
const ipResponse = await axios.get("https://ipapi.co/json/");
const city = ipResponse.data.city;
const { data } = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=899a6885afbf0702188ef94eb3204236&units=metric&lang=zh_cn`
);
this.temperature = parseInt(data.main.temp);
this.weather = data.weather[0].description;
const windDirection = this.getWindDirection(data.wind.deg);
const windSpeed = this.getWindSpeed(data.wind.speed);
this.wind = `${windDirection}${windSpeed}`;
this.humidity = data.main.humidity;
const timestamp = Date.now();
localStorage.setItem("weatherData", JSON.stringify({ data, timestamp }));
},
更多推荐
所有评论(0)