上一篇
html如何获取天气
- 行业动态
- 2024-04-03
- 3
获取天气信息可以通过调用天气API来实现,以下是一个使用HTML和JavaScript获取天气信息的示例:
1、你需要注册一个免费的天气API服务,例如OpenWeatherMap(https://openweathermap.org/)。
2、注册并登录你的账户,然后创建一个API密钥(API Key)。
3、在HTML文件中引入JavaScript代码,使用Fetch API来获取天气数据。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>获取天气信息</title>
</head>
<body>
<h1>获取天气信息</h1>
<div id="weatherInfo"></div>
<script>
// 替换为你的API密钥
const apiKey = 'your_api_key';
const city = '北京';
const url = https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=zh_cn
;
fetch(url)
.then(response => response.json())
.then(data => {
const weatherInfo = document.getElementById('weatherInfo');
weatherInfo.innerHTML = `
<h2>${data.name} 的天气信息</h2>
<table>
<tr>
<th>温度</th>
<td>${data.main.temp}°C</td>
</tr>
<tr>
<th>湿度</th>
<td>${data.main.humidity}%</td>
</tr>
<tr>
<th>气压</th>
<td>${data.main.pressure} hPa</td>
</tr>
<tr>
<th>风速</th>
<td>${data.wind.speed} m/s</td>
</tr>
<tr>
<th>风向</th>
<td>${data.wind.deg}°</td>
</tr>
<tr>
<th>天气描述</th>
<td>${data.weather[0].description}</td>
</tr>
</table>
`;
})
.catch(error => {
console.error('获取天气信息失败:', error);
});
</script>
</body>
</html>
在这个示例中,我们使用了OpenWeatherMap的API来获取天气信息,你需要将your_api_key
替换为你自己的API密钥,这个示例展示了如何获取温度、湿度、气压、风速、风向和天气描述等信息,并将这些信息显示在一个表格中。