const apiKey = "YOUR_API_KEY"; const weatherForm = document.querySelector("#weather-form"); const weatherInfo = document.querySelector("#weather-info"); fetchCurrent = async () => { const current = {}; await fetch("https://ipapi.co/json/") .then((response) => response.json()) .then((data) => { current["city"] = data.city; current["state"] = data.region; current["country"] = data.country_name; }) .catch((error) => { console.log(error); weatherInfo.innerHTML = "
An error occurred
"; }); return current; }; fetchCountry = async (country_code) => { let country; await fetch(`https://restcountries.com/v3.1/alpha/${country_code}`) .then((response) => response.json()) .then((data) => { country = data[0]; }) .catch((error) => { console.log(error); weatherInfo.innerHTML = "An error occurred
"; }); return country.name.common; }; fetchLocation = async (city, region, country_name, apiKey) => { let location; await fetch( `http://api.openweathermap.org/geo/1.0/direct?q=${city},${region},${country_name}&appid=${apiKey}` ) .then((response) => response.json()) .then((data) => { location = data[0]; }) .catch((error) => { console.log(error); weatherInfo.innerHTML = "An error occurred
"; }); if (!location) { location = { lat: 0, lon: 0 }; } else { location["country"] = await fetchCountry(location.country); } return location; }; fetchWeather = async (city, region, country_name, apiKey) => { const location = await fetchLocation(city, region, country_name, apiKey); let weather; await fetch( `https://api.openweathermap.org/data/2.5/weather?lat=${location.lat}&lon=${location.lon}&units=metric&&appid=${apiKey}` ) .then((response) => response.json()) .then((data) => { weather = data; }) .catch((error) => { console.log(error); weatherInfo.innerHTML = "An error occurred
"; }); if (location.state) weather[ "destination" ] = `${location.name}, ${location.state}, ${location.country}`; else weather["destination"] = `${location.name}, ${location.country}`; return weather; }; weatherForm.addEventListener("submit", async (event) => { event.preventDefault(); let city = document.querySelector("#city").value; let state = document.querySelector("#state").value; let country = document.querySelector("#country").value; if (city === "") { const current = await fetchCurrent(); city = current.city; state = current.state; country = current.country; } const weather = await fetchWeather(city, state, country, apiKey); if (weather.coord.lat === 0 && weather.coord.lon === 0) { weatherInfo.innerHTML = `Weather: ${weather.weather[0].main} (${weather.weather[0].description})
Temperature: ${weather.main.temp}°C
Feels like: ${weather.main.feels_like}°C
Pressure: ${weather.main.pressure}hPa
Humidity: ${weather.main.humidity}%
Visibility: ${weather.visibility}m
Wind speed: ${weather.wind.speed}m/s
Cloudiness: ${weather.clouds.all}%