如何在函数中结合OpenWeatherMap两个API请求获取天气预报?
实现步骤与代码示例
核心流程
- 接收用户输入的城市名
- 调用GeoCoding API,将城市名转换为经纬度
- 用拿到的经纬度调用OneCall Forecast API,获取天气数据
- 处理并展示天气数据
完整代码实现
1. 基础配置(替换成你的API密钥)
// 替换成你自己的OpenWeatherMap API密钥 const API_KEY = '你的API密钥';
2. 核心函数(两种写法)
写法一:链式Promise(适合理解异步流程)
function getWeatherByCity(cityName) { // 构造地理编码API请求URL const geoApiUrl = `https://api.openweathermap.org/geo/1.0/direct?q=${encodeURIComponent(cityName)}&limit=1&appid=${API_KEY}`; // 第一步:请求地理编码API获取经纬度 fetch(geoApiUrl) .then(response => { // 检查请求是否成功 if (!response.ok) { throw new Error('城市查找失败,请检查输入'); } return response.json(); }) .then(geoData => { // 检查是否返回有效地理数据 if (geoData.length === 0) { throw new Error('未找到该城市的地理信息'); } // 提取经纬度 const { lat, lon } = geoData[0]; // 构造天气预报API请求URL const forecastApiUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely&appid=${API_KEY}`; // 第二步:请求天气预报API return fetch(forecastApiUrl); }) .then(response => { if (!response.ok) { throw new Error('天气数据获取失败'); } return response.json(); }) .then(weatherData => { // 第三步:处理并展示天气数据 displayWeatherInfo(weatherData); }) .catch(error => { // 捕获所有错误并提示用户 console.error('错误信息:', error); alert(error.message); }); }
写法二:async/await(更直观的同步式写法)
async function getWeatherByCity(cityName) { try { // 1. 请求地理编码API const geoApiUrl = `https://api.openweathermap.org/geo/1.0/direct?q=${encodeURIComponent(cityName)}&limit=1&appid=${API_KEY}`; const geoResponse = await fetch(geoApiUrl); if (!geoResponse.ok) throw new Error('城市查找失败'); const geoData = await geoResponse.json(); if (geoData.length === 0) throw new Error('未找到该城市'); // 2. 提取经纬度,请求天气预报API const { lat, lon } = geoData[0]; const forecastApiUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely&appid=${API_KEY}`; const forecastResponse = await fetch(forecastApiUrl); if (!forecastResponse.ok) throw new Error('天气数据获取失败'); const weatherData = await forecastResponse.json(); // 3. 展示数据 displayWeatherInfo(weatherData); } catch (error) { console.error('错误:', error); alert(error.message); } }
3. 天气数据展示函数(示例)
function displayWeatherInfo(weatherData) { // 转换温度:Kelvin转摄氏度 const currentTemp = (weatherData.current.temp - 273.15).toFixed(1); const weatherDesc = weatherData.current.weather[0].description; const humidity = weatherData.current.humidity; // 把数据渲染到页面(假设页面有对应ID的元素) document.getElementById('city-temp').textContent = `${currentTemp}°C`; document.getElementById('weather-desc').textContent = weatherDesc; document.getElementById('humidity').textContent = `湿度:${humidity}%`; // 控制台打印完整数据,方便调试 console.log('完整天气数据:', weatherData); }
4. 绑定页面交互(示例)
假设页面有一个输入框和搜索按钮:
<input type="text" id="city-input" placeholder="输入城市名"> <button id="search-btn">查询天气</button> <div id="weather-result"> <p>温度:<span id="city-temp"></span></p> <p>天气:<span id="weather-desc"></span></p> <p><span id="humidity"></span></p> </div>
绑定点击事件:
document.getElementById('search-btn').addEventListener('click', () => { const cityName = document.getElementById('city-input').value.trim(); if (cityName) { getWeatherByCity(cityName); } else { alert('请输入城市名'); } });
新手注意事项
- API密钥替换:一定要把代码中的
你的API密钥换成你在OpenWeatherMap官网申请的密钥,否则请求会失败。 - 特殊字符处理:用
encodeURIComponent()处理城市名,避免城市名含空格、特殊字符导致URL错误(比如"New York"会被正确编码)。 - 跨域问题:本地直接打开HTML文件(file://协议)可能触发CORS错误,建议用VS Code的Live Server插件或本地服务器运行代码。
- 错误处理:代码中加入了错误捕获逻辑,能帮你快速定位问题(比如城市名拼写错误、API密钥无效等)。
内容的提问来源于stack exchange,提问作者BarkMulcher
相关产品推荐
相关产品推荐

