当前位置:首页 > JavaScript

js实现天气预报

2026-01-30 19:24:52JavaScript

使用 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 文件中:

js实现天气预报

<!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 密钥放在后端服务中
  • 对于中国用户,可考虑使用和风天气等国内服务商
  • 移动端需添加响应式设计

标签: 天气预报js
分享给朋友:

相关文章

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…

js 实现拖拽

js 实现拖拽

实现拖拽的基本步骤 在JavaScript中实现拖拽功能需要监听几个关键事件:mousedown、mousemove和mouseup。以下是实现的基本逻辑。 监听目标元素的mousedown事件,记…