当前位置:首页 > 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 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js 实现vue

js 实现vue

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

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现交换

js实现交换

交换变量的方法 在JavaScript中,交换两个变量的值有多种方法。以下是常见的几种实现方式: 使用临时变量 通过引入一个临时变量来存储其中一个变量的值,实现交换: let a = 1; le…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…