9 months ago
32 lines1.2 KiB
// Weather widget: type a city, get the temperature (Open-Meteo, no key needed) | |
const form = document.querySelector("#city-form"); | |
const output = document.querySelector("#weather"); | |
| |
async function coordinates(city) { | |
const res = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1`); | |
const data = await res.json(); | |
if (!data.results) throw new Error(`No city called ${city}`); | |
return data.results[0]; | |
} | |
| |
async function weather(place) { | |
const url = `https://api.open-meteo.com/v1/forecast?latitude=${place.latitude}&longitude=${place.longitude}¤t=temperature_2m,wind_speed_10m`; | |
const res = await fetch(url); | |
return (await res.json()).current; | |
} | |
| |
form.addEventListener("submit", async event => { | |
event.preventDefault(); | |
output.textContent = "Loading..."; | |
try { | |
const place = await coordinates(form.city.value); | |
const now = await weather(place); | |
output.textContent = `${place.name}: ${now.temperature_2m} °C, wind ${now.wind_speed_10m} km/h`; | |
} catch (err) { | |
output.textContent = err.message; | |
} | |
}); | |
| |
// This is the version we use in the video. | |
| |
// Try changing the values above and run it again. |