尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

利用开源工具在前端中调用接口,实现天气预报功能

利用开源工具在前端中调用接口,实现天气预报功能
📅 发布时间:2026/6/21 8:30:40

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

相关新闻

  • YOLOv8 CornerNet左上右下角点检测
  • 九轴姿态:MPU-9250九轴姿态解算全攻略
  • 四旋翼PID姿态控制实战指南

最新新闻

  • 铜陵市黄金回收白银回收铂金回收彩金回收哪家靠谱?2026年实地测评5家高人气实体门店推荐及联系方式 - 前途无量YY
  • 绍兴市黄金回收白银回收铂金回收彩金回收哪家靠谱?2026年实地测评5家高人气实体门店推荐及联系方式 - 前途无量YY
  • 金华市黄金回收白银回收铂金回收彩金回收哪家靠谱?2026年实地测评5家高人气实体门店推荐及联系方式 - 前途无量YY
  • 低表面亮度星系(LSB)的形成机制与环境影响研究
  • 廊坊市黄金回收店铺权威实力排行榜及电话地址推荐 2026年实测五家诚信优选实体门店 - 亦辰小黄鸭
  • 湖州市黄金回收白银回收铂金回收彩金回收哪家靠谱?2026年实地测评5家高人气实体门店推荐及联系方式 - 前途无量YY

日新闻

  • Visual C++运行库修复终极指南:5分钟快速解决Windows软件启动错误
  • 手把手教你构建统计局地区经济数据爬虫:从环境搭建到数据持久化全指南
  • 2026多Agent深度解析:用AI团队替代单一模型,四种架构实战落地

周新闻

  • Visual C++运行库修复终极指南:5分钟快速解决Windows软件启动错误
  • 手把手教你构建统计局地区经济数据爬虫:从环境搭建到数据持久化全指南
  • 2026多Agent深度解析:用AI团队替代单一模型,四种架构实战落地

月新闻

  • 【总结】入门篇:50句话让你记住架构核心概念
  • WeChatMsg技术方案解析:实现Mac微信数据自主管理的完整解决方案
  • WeChatMsg:革新性微信数据备份方案,打造你的专属数字记忆库

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号