js实现天气预报
使用 JavaScript 实现天气预报功能
获取天气 API
选择一个可靠的天气数据提供商,如 OpenWeatherMap、WeatherAPI 或 和风天气。注册账号获取 API Key。以 OpenWeatherMap 为例,其免费层提供基础天气数据。
前端页面结构
创建简单的 HTML 结构显示天气信息:
<div id="weather-container">
<h3>天气预报</h3>
<div id="location"></div>
<div id="temperature"></div>
<div id="description"></div>
<div id="icon"></div>
</div>
获取地理位置
使用浏览器 Geolocation API 获取用户位置:
navigator.geolocation.getCurrentPosition(
position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetchWeather(lat, lon);
},
error => {
console.error("Geolocation error:", error);
// 默认位置(如北京)
fetchWeather(39.9042, 116.4074);
}
);
调用天气 API
实现获取天气数据的函数:

async function fetchWeather(lat, lon) {
const apiKey = 'YOUR_API_KEY';
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
const data = await response.json();
displayWeather(data);
} catch (error) {
console.error("Weather fetch error:", error);
}
}
显示天气数据
处理 API 返回数据并更新页面:
function displayWeather(data) {
document.getElementById('location').textContent = `${data.name}, ${data.sys.country}`;
document.getElementById('temperature').textContent = `${Math.round(data.main.temp)}°C`;
document.getElementById('description').textContent = data.weather[0].description;
const iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
document.getElementById('icon').innerHTML = `<img src="${iconUrl}" alt="Weather icon">`;
}
添加样式
基础 CSS 样式增强显示效果:

#weather-container {
font-family: Arial, sans-serif;
max-width: 300px;
margin: 20px;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
text-align: center;
}
#temperature {
font-size: 2em;
font-weight: bold;
margin: 10px 0;
}
#description {
text-transform: capitalize;
margin-bottom: 10px;
}
错误处理
增强错误处理逻辑:
function displayError(message) {
const container = document.getElementById('weather-container');
container.innerHTML = `<div class="error">${message}</div>`;
container.style.color = 'red';
}
定时更新
设置定时刷新天气数据(注意 API 调用限制):
// 每小时更新一次
setInterval(() => {
navigator.geolocation.getCurrentPosition(
position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetchWeather(lat, lon);
}
);
}, 3600000);
完整示例
将所有代码整合到 HTML 文件中:
<!DOCTYPE html>
<html>
<head>
<title>天气预报</title>
<style>
#weather-container {
font-family: Arial, sans-serif;
max-width: 300px;
margin: 20px;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
text-align: center;
}
#temperature {
font-size: 2em;
font-weight: bold;
margin: 10px 0;
}
#description {
text-transform: capitalize;
margin-bottom: 10px;
}
.error {
color: red;
}
</style>
</head>
<body>
<div id="weather-container">
<h3>天气预报</h3>
<div id="location"></div>
<div id="temperature"></div>
<div id="description"></div>
<div id="icon"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetchWeather(lat, lon);
},
error => {
console.error("Geolocation error:", error);
fetchWeather(39.9042, 116.4074); // 默认位置
}
);
} else {
displayError("Geolocation is not supported by this browser.");
}
});
async function fetchWeather(lat, lon) {
const apiKey = 'YOUR_API_KEY';
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Weather data unavailable');
const data = await response.json();
displayWeather(data);
} catch (error) {
console.error("Weather fetch error:", error);
displayError("Unable to fetch weather data");
}
}
function displayWeather(data) {
document.getElementById('location').textContent = `${data.name}, ${data.sys.country}`;
document.getElementById('temperature').textContent = `${Math.round(data.main.temp)}°C`;
document.getElementById('description').textContent = data.weather[0].description;
const iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
document.getElementById('icon').innerHTML = `<img src="${iconUrl}" alt="Weather icon">`;
}
function displayError(message) {
const container = document.getElementById('weather-container');
container.innerHTML = `<div class="error">${message}</div>`;
}
</script>
</body>
</html>
注意事项
- 将
YOUR_API_KEY替换为实际的 API 密钥 - 免费 API 通常有调用频率限制
- 生产环境应考虑将 API 密钥放在后端服务中
- 对于中国用户,可考虑使用和风天气等国内服务商
- 移动端需添加响应式设计






