轻松搞定天气预报!开源工具+接口调用超详细教程

方案一:使用 OpenWeatherMap API + Axios(推荐)

  1. 获取 API Key
    首先到 OpenWeatherMap 注册并获取免费 API Key(每日 1000 次调用)

  2. 安装依赖
    image

  3. 基础实现
    `

天气预报

湿度: %
风速: m/s
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    const API_KEY = 'YOUR_API_KEY'; // 替换为你的 API Key
    
    async function getWeather() {
        const city = document.getElementById('cityInput').value;
        if (!city) {
            showError('请输入城市名称');
            return;
        }

        try {
            const response = await axios.get(
                `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}&lang=zh_cn`
            );
            
            displayWeather(response.data);
        } catch (error) {
            showError('获取天气信息失败,请检查城市名称或稍后重试');
            console.error('Error:', error);
        }
    }

    function displayWeather(data) {
        document.getElementById('error').textContent = '';
        document.getElementById('weatherInfo').style.display = 'block';
        
        document.getElementById('cityName').textContent = data.name;
        document.getElementById('temperature').textContent = `${Math.round(data.main.temp)}°C`;
        document.getElementById('weatherDescription').textContent = 
            data.weather[0].description;
        document.getElementById('humidity').textContent = data.main.humidity;
        document.getElementById('windSpeed').textContent = data.wind.speed;
    }

    function showError(message) {
        document.getElementById('error').textContent = message;
        document.getElementById('weatherInfo').style.display = 'none';
    }

    // 默认加载当前城市天气
    function getCurrentLocationWeather() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                async (position) => {
                    try {
                        const { latitude, longitude } = position.coords;
                        const response = await axios.get(
                            `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${API_KEY}&lang=zh_cn`
                        );
                        displayWeather(response.data);
                    } catch (error) {
                        showError('获取位置天气失败');
                    }
                },
                () => {
                    showError('无法获取您的位置,请手动输入城市');
                }
            );
        }
    }

    // 页面加载时获取位置
    window.onload = getCurrentLocationWeather;
</script>
`

方案二:使用和风天气(国内可用)

  1. 注册和风天气
    访问 和风天气开发平台 注册并获取 API Key
    `async function getQWeather(city) {
    const KEY = 'YOUR_HEFENG_KEY';

    // 1. 获取城市ID
    const locationRes = await axios.get(
    https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${KEY}
    );

    const cityId = locationRes.data.location[0].id;

    // 2. 获取实时天气
    const weatherRes = await axios.get(
    https://devapi.qweather.com/v7/weather/now?location=${cityId}&key=${KEY}
    );

    return weatherRes.data;
    }`

方案三:使用 Vue.js + 天气组件

  1. 安装 Vue 和天气组件
    image
  2. Vue 组件实现
    ` `

    方案四:使用 React + 天气库
    image

    `import React, { useState } from 'react';
    import axios from 'axios';

    function WeatherApp() {
    const [city, setCity] = useState('');
    const [weather, setWeather] = useState(null);
    const [error, setError] = useState('');

    const API_KEY = 'YOUR_API_KEY';

    const fetchWeather = async () => {
    try {
    const response = await axios.get(
    https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}&lang=zh_cn
    );
    setWeather(response.data);
    setError('');
    } catch (err) {
    setError('获取天气失败');
    setWeather(null);
    }
    };

    return (


    <input
    value={city}
    onChange={(e) => setCity(e.target.value)}
    placeholder="输入城市"
    />

      {weather && (
        <div className="weather-card">
          <h2>{weather.name}</h2>
          <div className="temp">{Math.round(weather.main.temp)}°C</div>
          <p>{weather.weather[0].description}</p>
          <div className="details">
            湿度: {weather.main.humidity}%
            风速: {weather.wind.speed} m/s
          </div>
        </div>
      )}
      
      {error && <div className="error">{error}</div>}
    </div>
    

    );
    }`

    功能增强建议:
    。增加功能
    7天预报
    空气质量指数
    日出日落时间
    天气图标展示
    。开源工具推荐
    图表: Chart.js 或 ECharts 显示温度趋势
    图标: Weather Icons 或 Font Awesome
    地图: Leaflet.js 显示天气地图
    。优化建议
    添加 loading 状态
    实现自动补全城市名称
    添加天气预警信息
    支持主题切换(白天/夜间模式)

    注意事项
    。API Key 安全: 不要在前端代码中暴露真实 API Key(生产环境应使用后端代理)
    。错误处理: 添加完善的错误处理和用户提示
    。用户体验: 添加加载动画和缓存机制
    。跨域问题: 使用 CORS 或 JSONP 解决跨域问题

posted @ 2025-12-31 19:49  why练习  阅读(1)  评论(0)    收藏  举报