js实现天气
使用 JavaScript 实现天气功能
获取天气数据
通过调用天气 API 获取实时天气数据。常见的免费天气 API 包括 OpenWeatherMap、WeatherAPI 等。注册并获取 API Key 后,可以使用 fetch 或 axios 发起请求。
const apiKey = 'YOUR_API_KEY';
const city = 'Beijing';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
displayWeather(data);
})
.catch(error => console.error('Error fetching weather data:', error));
显示天气信息
将获取的天气数据解析并显示在页面上。通常需要展示温度、天气状况、湿度、风速等信息。

function displayWeather(data) {
const weatherContainer = document.getElementById('weather-container');
const temperature = data.main.temp;
const description = data.weather[0].description;
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
weatherContainer.innerHTML = `
<h3>${data.name}</h3>
<p>Temperature: ${temperature}°C</p>
<p>Condition: ${description}</p>
<p>Humidity: ${humidity}%</p>
<p>Wind Speed: ${windSpeed} m/s</p>
`;
}
处理用户输入
允许用户输入城市名称并查询天气。可以通过表单和事件监听实现。

<input type="text" id="city-input" placeholder="Enter city name">
<button id="search-button">Search</button>
<div id="weather-container"></div>
document.getElementById('search-button').addEventListener('click', () => {
const city = document.getElementById('city-input').value;
if (city) {
fetchWeather(city);
}
});
function fetchWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => displayWeather(data))
.catch(error => console.error('Error:', error));
}
添加天气图标
根据天气状况显示对应的图标。OpenWeatherMap 提供了天气图标,可以直接使用。
function displayWeather(data) {
const weatherContainer = document.getElementById('weather-container');
const iconCode = data.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}@2x.png`;
weatherContainer.innerHTML = `
<h3>${data.name}</h3>
<img src="${iconUrl}" alt="${data.weather[0].description}">
<p>Temperature: ${data.main.temp}°C</p>
<p>Condition: ${data.weather[0].description}</p>
`;
}
错误处理
处理 API 请求失败或无效城市输入的情况。
function displayWeather(data) {
if (data.cod === '404') {
document.getElementById('weather-container').innerHTML = `<p>City not found</p>`;
return;
}
// 正常显示天气
}
通过以上步骤,可以实现一个基本的天气查询功能。根据需求可以进一步扩展,如添加天气预报、本地存储常用城市等。






