OpenWeather API 纬度和经度未返回正确的位置

问题描述 投票:0回答:1

我希望能够查找城市并获取天气信息,但是使用 OpenWeatherMap API,地理编码无法提供天气信息。它确实给出了纬度和经度,所以我从地理编码器中获取了纬度和经度并将其插入到普通的 API 中,但它给了我一个错误:{cod: '400', message: '错误的纬度'}

这是我的代码

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();

我不明白为什么要这样做。坐标数组中的坐标是正确的。我确实获取了他们给我的坐标并将其直接输入 apiURL。谁能向我解释一下吗?谢谢!

javascript api openweathermap weather-api
1个回答
0
投票

问题在于您在将坐标添加到列表之前创建了 url。

即使您稍后更新列表,字符串 url 也已被评估,因此它用

undefined
代替了纬度和经度。就像下面的片段一样。

const coord = [];
const apiURL = `https://api.openweathermap.org/data/2.5/weather?lat=${coord[0]}&lon=${coord[1]}`;

coord.push(1,2);

console.log(coord); // logs `[1,2]`
console.log(apiURL); // logs `https://api.openweathermap.org/data/2.5/weather?lat=undefined&lon=undefined`

您所要做的就是在坐标添加到列表后创建 url

© www.soinside.com 2019 - 2024. All rights reserved.