当前位置:首页 > 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

实现获取天气数据的函数:

js实现天气预报

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 样式增强显示效果:

js实现天气预报

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

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

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url,…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整…

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…