You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenWeather API经纬度调用天气接口返回400错误求助

OpenWeatherMap API调用出现"wrong latitude"错误排查

问题描述

我想通过城市名查询天气信息,使用OpenWeatherMap的地理编码接口获取经纬度后,传入常规天气API却收到错误:

{cod: '400', message: 'wrong latitude'}

我的代码如下:

const apiKey = '';

async function weather(){
    coord = [];
    const apiURL = await `https://api.openweathermap.org/data/2.5/weather?lat=${coord[0]}&lon=${coord[1]}&appid=${apiKey}`;

    const geoURL = `http://api.openweathermap.org/geo/1.0/direct?q=London&appid=${apiKey}`;

    try{
        const geoData = await fetch(geoURL);
        const geoResult = await geoData.json();
        console.log(geoResult);
        geoResult.forEach(att => {
            var lat = att.lat;
            var lon = att.lon;
            coord.push(lat);
            coord.push(lon);
        })
        console.log(coord);
        const data = await fetch(apiURL);
        const result = await data.json();
        console.log(result);
    }

    catch(err){
        console.log(err);
    }

    finally{
        console.log('finally block');
    }
}

weather();

我不明白为何会出现这个错误,coord数组中的经纬度是正确的,直接使用了地理编码接口返回的坐标传入apiURL,恳请有人解释原因。


错误原因

你在定义apiURL时,coord数组还是空的,此时coord[0]和coord[1]的值都是undefined,拼接出来的天气API URL中lat参数是无效值,因此触发了"wrong latitude"的400错误。

修复方案

将apiURL的定义移到获取到有效经纬度之后,确保URL使用的是地理编码返回的正确坐标。同时优化代码避免不必要的数组操作和全局变量问题:

const apiKey = '';

async function weather(){
    const geoURL = `http://api.openweathermap.org/geo/1.0/direct?q=London&appid=${apiKey}`;

    try{
        const geoData = await fetch(geoURL);
        const geoResult = await geoData.json();
        console.log(geoResult);
        
        // 地理编码可能返回多个结果,取第一个匹配项即可
        if (!geoResult.length) {
            throw new Error('未找到匹配的城市');
        }
        const { lat, lon } = geoResult[0];
        console.log(lat, lon);
        
        // 此时再拼接天气API请求URL
        const apiURL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`;
        const data = await fetch(apiURL);
        const result = await data.json();
        console.log(result);
    }

    catch(err){
        console.log(err);
    }

    finally{
        console.log('finally block');
    }
}

weather();

额外优化点

  • 地理编码接口可能返回多个城市结果,直接使用forEach会把所有经纬度存入数组,导致后续坐标混乱,建议取第一个匹配结果。
  • 原代码中coord变量未用let/const声明,会成为全局变量,增加代码风险,修复后直接解构获取经纬度,无需额外数组存储。

内容的提问来源于stack exchange,提问作者FroggyGroggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:30:25