当前位置: 首页 > news >正文

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

方案一:使用 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 Keyasync 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 解决跨域问题

http://www.jsqmd.com/news/172878/

相关文章:

  • 日语助动词与名词、形容词与动词的变形之间的关系
  • 样本库的管理者最担心什么?是温度波动吗?还是湿度异常呢?
  • 日语动词的意志型、可能型、假定型、被动型、使役型
  • vue基于ASP.NET的在线图书馆信息图书借阅管理系统_m9947
  • 超宽带UWB定位模组通信原理、应用方案及选型指南解析
  • 日语助动词和补助动词的区别
  • 【编码器信号】滤波前后差别你必须知道-PART-编码器-噪声
  • 作业:打印乘法表
  • 2025年高性能音频传输模块选购指南与应用方案推荐
  • 作业:求10 个整数中最大值
  • vue基于c#的高校学生成绩管理系统的设计与实现
  • 机器学习领袖谈AI普及与多元化发展
  • MySql 5.7 索引不存在则创建,存在则忽略
  • 2025年UWB超宽带定位模块产品技术对比与应用方案解析
  • vue基于Python+Django的高校考培中心考试培训管理服务系统
  • cookie操作类(加密,获取,删除)
  • 解决 Tauri 中 shell.open 报错:Uncaught (in promise) shell.open not allowed URL
  • 小学生刚近视!怎么让孩子近视度数涨得慢些?
  • 博客的烟火气:在技术、生活与热爱之间找到平衡点
  • 基于深度学习的杂草检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
  • 高频隔离型光伏离网单相逆变器控制算法探究
  • 小学生近视加深太快怎么控制?这些方法你用对了吗?
  • Tauri框架入门:基本概念与快速使用指南
  • Linux top 命令详解:系统监控的必备工具
  • 西门子Smart200 PLC 自抗扰控制(ADRC):超越传统的PID算法
  • 邮件错发怎么办 撤回防泄密关键一步!
  • 智能化锂矿选矿线:接近传感器的耐磨挑战
  • vue基于python的牛奶品牌商城评价积分系统_r144o
  • Faulhaber Coreless 直流电机 2338S006 使用指南-PART-MOTOR-derivative feedback
  • 【linux】Linux系统中双连字符 --的主要作用