
本文详解 OpenWeather 地理编码(Geocoding)与天气 API 的协同调用流程,重点解决因 URL 提前拼接导致的 wrong latitude 错误,并提供可直接运行的修复代码与最佳实践。
本文详解 openweather 地理编码(geocoding)与天气 api 的协同调用流程,重点解决因 url 提前拼接导致的 `wrong latitude` 错误,并提供可直接运行的修复代码与最佳实践。
在使用 OpenWeather API 实现“城市名 → 天气数据”功能时,常见的做法是分两步:先通过地理编码 API(/geo/1.0/direct)获取目标城市的经纬度,再将经纬度代入天气 API(/data/2.5/weather)请求实时天气。然而,许多开发者会遇到 {"cod": "400", "message": "wrong latitude"} 这类错误——根本原因并非坐标本身错误,而是 URL 字符串在坐标尚未就绪时就被提前定义并固化了。
在原始代码中,apiURL 被声明在 coord = [] 之后、但远早于 coord.push(lat, lon) 执行之前:
const coord = [];
// ❌ 错误:此时 coord[0] 和 coord[1] 均为 undefined,apiURL 已生成含 "lat=undefined&lon=undefined" 的无效地址
const apiURL = `https://api.openweathermap.org/data/2.5/weather?lat=${coord[0]}&lon=${coord[1]}&appid=${apiKey}`;
// ...后续才向 coord 写入数据
geoResult.forEach(att => {
coord.push(att.lat, att.lon); // ✅ 此时 coord 才有值
});
由于 JavaScript 模板字符串在定义时即完成求值(而非运行时动态读取),apiURL 中的 ${coord[0]} 始终是 undefined,最终请求发送的是形如 ?lat=undefined&lon=undefined 的非法参数,OpenWeather 服务端自然返回 400 错误。
✅ 正确做法是:将天气 API 的 URL 构建逻辑延迟至坐标获取完成之后,确保变量已赋值。以下是修复后的完整代码(含健壮性增强):
const apiKey = 'YOUR_API_KEY'; // 替换为你的有效 API Key
async function getWeatherByCity(cityName) {
try {
// Step 1: 调用地理编码 API 获取坐标
const geoURL = `https://api.openweathermap.org/geo/1.0/direct?q=${encodeURIComponent(cityName)}&limit=1&appid=${apiKey}`;
const geoRes = await fetch(geoURL);
if (!geoRes.ok) throw new Error(`Geocoding failed: ${geoRes.status} ${geoRes.statusText}`);
const geoData = await geoRes.json();
if (!geoData.length) throw new Error(`No location found for "${cityName}"`);
const { lat, lon } = geoData[0]; // 取首个匹配结果(最相关)
console.log(`Resolved "${cityName}" → lat: ${lat}, lon: ${lon}`);
// Step 2: ✅ 在确认 lat/lon 存在后,再构建天气 API URL
const weatherURL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`; // units=imperial 可选
const weatherRes = await fetch(weatherURL);
if (!weatherRes.ok) throw new Error(`Weather API error: ${weatherRes.status}`);
const weatherData = await weatherRes.json();
console.log('Weather data:', {
city: weatherData.name,
temp: weatherData.main.temp,
condition: weatherData.weather[0].description,
humidity: weatherData.main.humidity
});
return weatherData;
} catch (err) {
console.error('❌ Weather lookup failed:', err.message);
throw err;
}
}
// 调用示例
getWeatherByCity('London');
? 关键注意事项:
-
URL 动态构建时机:所有依赖异步获取数据的 URL,必须在
await后、数据变量确定有效后再拼接; -
错误处理:务必检查
fetch响应状态(res.ok)及地理编码返回数组长度,避免空坐标引发后续错误; -
参数安全:对城市名使用
encodeURIComponent()防止特殊字符(如空格、中文)破坏 URL 结构; -
单位设置:添加
&units=metric(摄氏)或&units=imperial(华氏)以获得更直观温度值; - API Key 保护:生产环境切勿硬编码 Key,应通过环境变量或后端代理调用。
通过遵循上述结构与原则,即可稳定、可靠地实现从城市名称到精准天气数据的端到端查询,彻底规避 wrong latitude 类错误。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!









