html如何获取天气

获取天气信息可以通过调用天气API来实现,以下是一个使用HTML和JavaScript获取天气信息的示例:,1、你需要注册一个免费的天气API服务,例如OpenWeatherMap(https://openweathermap.org/)。,2、注册并登录你的账户,然后创建一个API密钥(API Key)。,3、在HTML文件中引入JavaScript代码,使用Fetch API来获取天气数据。,在这个示例中,我们使用了OpenWeatherMap的API来获取天气信息,你需要将
your_api_key替换为你自己的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>,

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《html如何获取天气》
文章链接:https://zhuji.vsping.com/426735.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。