js获取所在城市天气信息
时间: 2023-06-17 16:06:46 浏览: 52
要获取所在城市的天气信息,需要使用第三方API。以下是一种获取城市天气信息的方式:
1. 首先,需要获取用户所在位置的经纬度信息。可以使用HTML5的Geolocation API来实现:
```js
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// 在这里调用获取天气信息的函数,传入经纬度参数
}
```
2. 接下来,使用第三方天气API获取天气信息。这里以和风天气API为例:
```js
function getCityWeather(lat, lon) {
var url = "https://free-api.heweather.net/s6/weather/now?location=" + lat + "," + lon + "&key=YOUR_API_KEY";
// 替换 YOUR_API_KEY 为你在和风天气申请的 API Key
fetch(url)
.then(response => response.json())
.then(data => {
// 在这里处理获取到的天气信息
console.log(data);
})
.catch(error => console.error(error));
}
```
3. 最后,根据获取到的天气信息,更新页面显示。
完整代码如下:
```js
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
getCityWeather(lat, lon);
}
function getCityWeather(lat, lon) {
var url = "https://free-api.heweather.net/s6/weather/now?location=" + lat + "," + lon + "&key=YOUR_API_KEY";
// 替换 YOUR_API_KEY 为你在和风天气申请的 API Key
fetch(url)
.then(response => response.json())
.then(data => {
var city = data.HeWeather6[0].basic.location;
var weather = data.HeWeather6[0].now.cond_txt;
var temp = data.HeWeather6[0].now.tmp;
// 在这里更新页面显示
document.getElementById("city").textContent = city;
document.getElementById("weather").textContent = weather;
document.getElementById("temp").textContent = temp;
})
.catch(error => console.error(error));
}
```
需要注意的是,和风天气API需要申请API Key才能使用。如果你想使用其他天气API,需要查看对应API的文档来获取使用方法和申请API Key。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)