|
| 1 | +// Get your own ApiKey from https://openweathermap.org/api |
| 2 | +const apikey = "3265874a2c77ae4a04bb96236a642d2f"; |
| 3 | + |
| 4 | +// Grab objects via DOM |
| 5 | +const main = document.getElementById("main"); |
| 6 | +const form = document.getElementById("form"); |
| 7 | +const search = document.getElementById("search"); |
| 8 | + |
| 9 | +// Function that returns weatherdata |
| 10 | +const url = (city) => |
| 11 | + `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`; // |
| 12 | + |
| 13 | +async function getWeatherByLocation(city) { |
| 14 | + const resp = await fetch(url(city), { origin: "cors" }); |
| 15 | + const respData = await resp.json(); |
| 16 | + |
| 17 | + console.log(respData); |
| 18 | + |
| 19 | + addWeatherToPage(respData); |
| 20 | +} |
| 21 | + |
| 22 | +// Display the weather data |
| 23 | +function addWeatherToPage(data) { |
| 24 | + const temp = KtoC(data.main.temp); |
| 25 | + |
| 26 | + // DOM manipulation |
| 27 | + const weather = document.createElement("div"); |
| 28 | + weather.classList.add("weather"); |
| 29 | + |
| 30 | + weather.innerHTML = ` |
| 31 | + <h2><img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /></h2> |
| 32 | + <small>${data.weather[0].main}</small> |
| 33 | + `; |
| 34 | + |
| 35 | + // cleanup |
| 36 | + main.innerHTML = ""; |
| 37 | + |
| 38 | + main.appendChild(weather); |
| 39 | +} |
| 40 | + |
| 41 | +// Temperature conversion |
| 42 | +function KtoC(K) { |
| 43 | + return Math.floor(K - 273.15); |
| 44 | +} |
| 45 | + |
| 46 | +// Event listener for form submission |
| 47 | +form.addEventListener("submit", (e) => { |
| 48 | + e.preventDefault(); |
| 49 | + |
| 50 | + const city = search.value; |
| 51 | + |
| 52 | + if (city) { |
| 53 | + getWeatherByLocation(city); |
| 54 | + } |
| 55 | +}); |
0 commit comments