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

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

利用开源工具在前端中调用接口,实现天气预报功能
📅 发布时间:2026/7/22 9:54:43

方案一:使用 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姿态控制实战指南

最新新闻

  • SmartSub:本地优先AI字幕工具的技术解析与应用
  • Power BI中关于度量值专用表单的建立
  • Unity Slate插件自定义轨道开发:构建动态战斗动画与伤害系统
  • 2026宁波绍兴全品类电子设备回收公司30分钟上门实测 - LYL仔仔
  • Unity RenderFeature开发避坑指南:五大误区与实战解决方案
  • KubeEdge:边缘计算与Kubernetes的融合实践

日新闻

  • AI云原生实战05-金融AI上云最难的不是技术,是“不出事“——TCE银行风控架构拆解
  • 2026年GEOSEO优化公司选型深度测评:五大硬核标准严选,这六家重塑搜索增长新格局 - 品牌前沿专家
  • **核验!2026年7月卡地亚香港**售后网点地址及服务电话公告 - 卡地亚服务中心

周新闻

  • SaaS软件行业GEO实践:AI搜索时代的品牌可见性与获客新路径
  • 什么是PCTFE?医药高端包装的“防潮王牌“材料
  • 【JVM调优实战】16-可视化利器-JConsole-VisualVM-JMC

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

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

服务项目

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

快速链接

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

联系方式

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

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