Add lesson 9: Project: weather widget

Daniel Tanaka 1 year ago
parent af52117bf0 commit 46d44ba84c975b8496bb83a4e926950bb9d787c9
4 changed files with 67 additions and 0 deletions
+19-0lessons/09-project-weather-widget/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 9: Project: weather widget
2+
3+We look at project: weather widget the way working developers use it, with examples you can change and run right away.
4+
5+Full lesson: [https://glibcode.net/courses/javascript-web/lessons/9](https://glibcode.net/courses/javascript-web/lessons/9)
6+
7+## Files
8+
9+- `weather.js`: the course project: a weather widget for any city
10+
11+## Run it
12+
13+```sh
14+npx serve . # then open http://localhost:3000 and the browser console
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/09-project-weather-widget/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 9
2+
3+1. Add a check that prints a warning when a result looks wrong (negative, empty, too big).
4+2. What happens with an empty input? Change the code so it handles that case with a clear message.
5+3. Run `weather.js` and change one value. Write down what you expect, then run it again and compare.
+15-0lessons/09-project-weather-widget/index.html ADDED
@@ -0,0 +1,15 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+ <meta charset="utf-8">
5+ <title>Weather widget</title>
6+</head>
7+<body>
8+ <form id="city-form">
9+ <input name="city" placeholder="City" required>
10+ <button>Show weather</button>
11+ </form>
12+ <p id="weather"></p>
13+ <script src="weather.js"></script>
14+</body>
15+</html>
+28-0lessons/09-project-weather-widget/weather.js ADDED
@@ -0,0 +1,28 @@
1+// Weather widget: type a city, get the temperature (Open-Meteo, no key needed)
2+const form = document.querySelector("#city-form");
3+const output = document.querySelector("#weather");
4+
5+async function coordinates(city) {
6+ const res = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1`);
7+ const data = await res.json();
8+ if (!data.results) throw new Error(`No city called ${city}`);
9+ return data.results[0];
10+}
11+
12+async function weather(place) {
13+ const url = `https://api.open-meteo.com/v1/forecast?latitude=${place.latitude}&longitude=${place.longitude}&current=temperature_2m,wind_speed_10m`;
14+ const res = await fetch(url);
15+ return (await res.json()).current;
16+}
17+
18+form.addEventListener("submit", async event => {
19+ event.preventDefault();
20+ output.textContent = "Loading...";
21+ try {
22+ const place = await coordinates(form.city.value);
23+ const now = await weather(place);
24+ output.textContent = `${place.name}: ${now.temperature_2m} °C, wind ${now.wind_speed_10m} km/h`;
25+ } catch (err) {
26+ output.textContent = err.message;
27+ }
28+});