-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
128 lines (109 loc) · 4.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import express from "express";
import fetch from "node-fetch";
import path from "path";
const app = express();
app.set("view engine", "ejs");
app.set("views", "./views");
app.use(express.static("public"));
function getTime(dateTimeString) {
const dateTime = new Date(dateTimeString);
const time = dateTime.toLocaleTimeString("en-GB", {
hour: "numeric",
minute: "numeric",
});
return time;
}
async function fetchCoordinates(name) {
const locationUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${name}&count=1&language=nl&format=json`;
try {
const response = await fetch(locationUrl);
const data = await response.json();
if (data.results && data.results.length > 0) {
const latitude = data.results[0].latitude;
const longitude = data.results[0].longitude;
const admin1 = data.results[0].admin1;
const country = data.results[0].country;
return { latitude, longitude, admin1 ,country };
} else {
throw new Error("Geen resultaten gevonden voor de opgegeven plaats.");
}
} catch (error) {
console.error("Fout bij het ophalen van coördinaten:", error);
throw error;
}
}
// Maakt een route voor de overzichtspagina
app.get("/", (request, response) => {
const searchTerm = request.query.name;
// Maakt een verzoek naar de externe API
fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${searchTerm}&count=50&language=nl&format=json`)
.then(response => response.json())
.then(data => {
const resultsWithLinks = data.results.map(result => {
const link = `/forecast?name=${encodeURIComponent(result.name)}&lat=${result.latitude}&lon=${result.longitude}`;
return { ...result, link };
});
response.render('index', { results: resultsWithLinks || [] });
})
.catch(error => {
console.log(error);
response.render('error');
});
});
// Maakt een route voor de detailpagina
app.get("/forecast", async (request, response) => {
const id = request.query.id;
const name = request.query.name;
try {
const { latitude, longitude, admin1 , country } = await fetchCoordinates(name);
const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=temperature_2m,dewpoint_2m,apparent_temperature,precipitation_probability,precipitation,weathercode,surface_pressure,cloudcover,visibility,windspeed_10m,soil_temperature_6cm,soil_moisture_27_81cm&daily=sunrise,sunset,uv_index_max&language=nl`;
const currentWeatherUrl =
weatherUrl +
"¤t_weather=true&timezone=Europe%2FBerlin&forecast_days=1";
const currentWeather = await fetchJson(currentWeatherUrl);
const time = currentWeather.hourly.time[0].split("T")[1];
const sunriseTime = currentWeather.daily.sunrise[0].split("T")[1];
const sunsetTime = currentWeather.daily.sunset[0].split("T")[1];
const precipitation = currentWeather.hourly.precipitation;
const apparentTemperature = currentWeather.hourly.apparent_temperature;
const precipitationProbability =
currentWeather.hourly.precipitation_probability;
const surfacePressure = currentWeather.hourly.surface_pressure;
const surfaceTemperature = currentWeather.hourly.soil_temperature_6cm;
const visibility = currentWeather.hourly.visibility;
const soilMoisture = currentWeather.hourly.soil_moisture_27_81cm;
const viewsDir = path.resolve("./views");
response.render(path.join(viewsDir, "forecast.ejs"), {
id,
time,
sunriseTime,
sunsetTime,
precipitation,
apparent_temperature: apparentTemperature,
precipitation_probability: precipitationProbability,
surface_pressure: surfacePressure,
surface_temperature: surfaceTemperature,
current_weather: currentWeather.current_weather,
visibility,
soilMoisture,
hourly: currentWeather.hourly,
daily: currentWeather.daily,
name,
admin1,
country,
getTime,
});
console.log(weatherUrl)
} catch (error) {
console.error(error);
response
.status(500)
.send("Geen resultaten gevonden voor de opgegeven plaats.");
}
});
app.listen(8000, () => {
console.log("Server gestart op http://localhost:8000");
});
async function fetchJson(url, payload = {}) {
return await fetch(url, payload).then((response) => response.json());
}