I want to be able to look up a city and get the weather information, but with the OpenWeatherMap API, the Geocoding doesn't give the weather information. It does give the latitude and longitude, so I took the latitude and longitude from the Geocoder and plugged it into the normal API, but it gave me an error:
{cod: '400', message: 'wrong latitude'}
Here is my code:
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();
I don't see why it is doing that. The coordinates in the coord
array is correct. I literally took the coordinates that they gave me and fed it straight to apiURL
. Can anyone please explain this to me?
The issue lays in the fact that you create url before adding coordinates to the list.
Even if you update the list later, the string url has already been evaluated so it has undefined
in place of lat and lon. Like in the snippet below.
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`
All you have to do is create url after coordinates have been added to the list