-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
367 lines (334 loc) · 12.5 KB
/
app.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// Selectors
const timeElement = document.getElementById("time");
const dateElement = document.getElementById("date");
const currTemperatureElement = document.getElementById("current-temperature");
const feelTemperatureElement = document.getElementById("feels-temperature");
const generalWeatherIconElement = document.getElementById(
"general-weather-info-icon"
);
const generalWeatherTextElement = document.getElementById(
"general-weather-info-text"
);
const futureForecastListElement = document.getElementById(
"future-forecast-list"
);
const pressureElement = document.getElementById("pressure");
const humidityElement = document.getElementById("humidity");
const windElement = document.getElementById("wind");
const locationInputButton = document.getElementById("location-search-btn");
const locationInputElement = document.getElementById("location");
// Global Variables
let lastValidCity = "Maldives";
let backgroundImageRes = "1600x900";
let mobileScreenMediaQueryElement = window.matchMedia("(max-width: 768px)");
// Constants
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
const WIND_DIRECTION_TEXT = [
"N",
"NNE",
"NE",
"ENE",
"E",
"ESE",
"SE",
"SSE",
"S",
"SSW",
"SW",
"WSW",
"W",
"WNW",
"NW",
"NNW",
"N",
];
const WIND_CARDINAL_DIRECTIONS = [
"↑ N",
"↗ NE",
"→ E",
"↘ SE",
"↓ S",
"↙ SW",
"← W",
"↖ NW",
];
const OPEN_WEATHER_API_ICONS_TO_WU_ICONS = {
// Day
"01d": `<i class="wu wu-white wu-128 wu-sunny"></i>`,
"02d": `<i class="wu wu-white wu-128 wu-partlycloudy"></i>`,
"03d": `<i class="wu wu-white wu-128 wu-cloudy"></i>`,
"04d": `<i class="wu wu-white wu-128 wu-cloudy"></i>`,
"09d": `<i class="wu wu-white wu-128 wu-chancerain"></i>`,
"10d": `<i class="wu wu-white wu-128 wu-rain"></i>`,
"11d": `<i class="wu wu-white wu-128 wu-tstorms"></i>`,
"13d": `<i class="wu wu-white wu-128 wu-snow"></i>`,
"50d": `<i class="wu wu-white wu-128 wu-hazy"></i>`,
// Night
"01n": `<i class="wu wu-white wu-128 wu-sunny wu-night"></i>`,
"02n": `<i class="wu wu-white wu-128 wu-partlycloudy wu-night"></i>`,
"03n": `<i class="wu wu-white wu-128 wu-cloudy wu-night"></i>`,
"04n": `<i class="wu wu-white wu-128 wu-cloudy wu-night"></i>`,
"09n": `<i class="wu wu-white wu-128 wu-chancerain wu-night"></i>`,
"10n": `<i class="wu wu-white wu-128 wu-rain wu-night"></i>`,
"11n": `<i class="wu wu-white wu-128 wu-tstorms wu-night"></i>`,
"13n": `<i class="wu wu-white wu-128 wu-snow wu-night"></i>`,
"50n": `<i class="wu wu-white wu-128 wu-hazy wu-night"></i>`,
};
const OPEN_WEATHER_API_ICONS_TO_WU_ICONS_64_PX = {
// Day
"01d": `<i class="wu wu-white wu-64 wu-sunny"></i>`,
"02d": `<i class="wu wu-white wu-64 wu-partlycloudy"></i>`,
"03d": `<i class="wu wu-white wu-64 wu-cloudy"></i>`,
"04d": `<i class="wu wu-white wu-64 wu-cloudy"></i>`,
"09d": `<i class="wu wu-white wu-64 wu-chancerain"></i>`,
"10d": `<i class="wu wu-white wu-64 wu-rain"></i>`,
"11d": `<i class="wu wu-white wu-64 wu-tstorms"></i>`,
"13d": `<i class="wu wu-white wu-64 wu-snow"></i>`,
"50d": `<i class="wu wu-white wu-64 wu-hazy"></i>`,
// Night
"01n": `<i class="wu wu-white wu-64 wu-sunny wu-night"></i>`,
"02n": `<i class="wu wu-white wu-64 wu-partlycloudy wu-night"></i>`,
"03n": `<i class="wu wu-white wu-64 wu-cloudy wu-night"></i>`,
"04n": `<i class="wu wu-white wu-64 wu-cloudy wu-night"></i>`,
"09n": `<i class="wu wu-white wu-64 wu-chancerain wu-night"></i>`,
"10n": `<i class="wu wu-white wu-64 wu-rain wu-night"></i>`,
"11n": `<i class="wu wu-white wu-64 wu-tstorms wu-night"></i>`,
"13n": `<i class="wu wu-white wu-64 wu-snow wu-night"></i>`,
"50n": `<i class="wu wu-white wu-64 wu-hazy wu-night"></i>`,
};
const hPA_TO_mm_Hg_CONVERSION_RATE = 0.75006157584566;
const API_KEY = "95860a4ff88ebd043ec824b1f84e3872";
// Add Event Listener
locationInputButton.addEventListener("click", handleLocationInput);
locationInputElement.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
locationInputButton.click();
}
});
mobileScreenMediaQueryElement.addEventListener(
"change",
updateBackgroundImageResBasedOnMediaQuery
);
// Refresh data every one second
setInterval(refreshAllData, 1000);
refreshAllData();
safeLoadWeatherData(lastValidCity, (firstCall = true));
// Helper Functions
function refreshAllData() {
let { hour, minutes, ampm, day, date, month, year } = getDateTimeData();
({ hour, minutes } = formatHourMinutes(hour, minutes));
timeElement.innerHTML = `${hour}:${minutes} ${ampm}`;
dateElement.innerHTML = `${DAYS[day]}, ${date} ${MONTHS[month]} ${year}`;
}
function getDateTimeData() {
let currDateTime = new Date();
let year = currDateTime.getFullYear();
let month = currDateTime.getMonth();
let date = currDateTime.getDate();
let day = currDateTime.getDay();
let hour = currDateTime.getHours();
let minutes = currDateTime.getMinutes();
let ampm = hour < 12 ? "AM" : "PM";
return { hour, minutes, ampm, day, date, month, year };
}
function formatHourMinutes(hour, minutes) {
hour = hour >= 12 ? hour - 12 : hour;
hour = hour === 0 ? 12 : hour;
hour = hour < 10 ? `0${hour}` : hour;
minutes = minutes < 10 ? `0${minutes}` : minutes;
return { hour, minutes };
}
async function getWeatherData(cityName) {
let { latitude, longitude } = await getLatiLongFromCityName(cityName);
let api_one_call_weather_url = `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&units=metric&appid=${API_KEY}`;
let res;
try {
res = await fetch(api_one_call_weather_url);
} catch (err) {
throw "Failed to Fetch";
}
let data = await res.json();
return data;
}
async function getLatiLongFromCityName(cityName) {
let api_geocoding_url = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&appid=${API_KEY}`;
let latitude, longitude;
let res;
try {
res = await fetch(api_geocoding_url);
} catch (err) {
throw "Failed to Fetch";
}
let data = await res.json();
if (data.length === 0) {
throw "City not found!";
}
latitude = data[0]["lat"];
longitude = data[0]["lon"];
return { latitude, longitude };
}
async function handleLocationInput(event) {
event.preventDefault();
await safeLoadWeatherData(locationInputElement.value);
}
async function safeLoadWeatherData(cityName, firstCall = false) {
try {
await getAndUpdateWeatherData(cityName, firstCall);
resetInputElement(cityName);
} catch (err) {
resetInputElement("Err: " + err);
}
}
function resetInputElement(placeholder, value = "") {
locationInputElement.placeholder = placeholder;
locationInputElement.value = value;
}
async function getAndUpdateWeatherData(cityName, firstCall) {
let weatherData = await getWeatherData(cityName);
updateCurrentWeatherData(weatherData);
updateFutureForecastWeatherData(weatherData);
if (!firstCall) {
updateBackgroundImage(cityName);
}
lastValidCity = cityName;
}
function updateCurrentWeatherData(weatherData) {
let currentWeatherData = weatherData.current;
updateTemperatureData(currentWeatherData);
updateGeneralWeatherInfo(currentWeatherData);
updateAdditionalWeatherInfo(currentWeatherData);
}
function updateFutureForecastWeatherData(weatherData) {
futureForecastListElement.innerHTML = "";
weatherData.daily.forEach((dailyForecast, idx) => {
let futureForecastElement = createFutureForecastElement(dailyForecast);
setTimeout(() => {
futureForecastListElement.appendChild(futureForecastElement);
}, idx * 100);
});
}
function createFutureForecastElement(dailyForecast) {
let weather = dailyForecast.weather[0];
let futureForecastElement = document.createElement("div");
futureForecastElement.classList.add("future-forecast-item");
let futureForecastElementDay =
createFutureForecastDayElement(dailyForecast);
futureForecastElement.appendChild(futureForecastElementDay);
let futureForecastElementIcon = createFutureForecastIconElement(weather);
futureForecastElement.appendChild(futureForecastElementIcon);
let futureForecastElementTemp =
createFutureForecastTempElement(dailyForecast);
futureForecastElement.appendChild(futureForecastElementTemp);
let futureForecastElementWeather =
createFutureForecastWeatherElement(weather);
futureForecastElement.appendChild(futureForecastElementWeather);
return futureForecastElement;
}
function createFutureForecastDayElement(dailyForecast) {
let futureForecastElementDay = document.createElement("div");
futureForecastElementDay.classList.add("future-forecast-day");
let day = new Date(dailyForecast["dt"] * 1000).getDay();
futureForecastElementDay.innerText = DAYS[day];
return futureForecastElementDay;
}
function createFutureForecastIconElement(weather) {
let futureForecastElementIcon = document.createElement("div");
futureForecastElementIcon.classList.add("future-forecast-icon");
futureForecastElementIcon.innerHTML =
OPEN_WEATHER_API_ICONS_TO_WU_ICONS_64_PX[weather["icon"]];
return futureForecastElementIcon;
}
function createFutureForecastTempElement(dailyForecast) {
let futureForecastElementTemp = document.createElement("div");
futureForecastElementTemp.classList.add("future-forecast-temperature");
futureForecastElementTemp.innerHTML = `${Math.round(
dailyForecast["temp"]["min"]
)}<span>°</span> / ${Math.round(
dailyForecast["temp"]["max"]
)}<span>°</span>`;
return futureForecastElementTemp;
}
function createFutureForecastWeatherElement(weather) {
let futureForecastElementWeather = document.createElement("div");
futureForecastElementWeather.classList.add("future-forecast-general-info");
futureForecastElementWeather.innerHTML = capitalizeFirstLetter(
weather["description"]
);
return futureForecastElementWeather;
}
function updateBackgroundImageResBasedOnMediaQuery(mediaQuery) {
if (mediaQuery.matches) {
backgroundImageRes = "900x1600";
} else {
backgroundImageRes = "1600x900";
}
let currPlaceholder = locationInputElement.placeholder;
if (!currPlaceholder.includes("Err: ")) {
updateBackgroundImage(currPlaceholder);
} else {
updateBackgroundImage(lastValidCity);
}
}
function updateBackgroundImage(cityName) {
document.body.style.backgroundImage =
"url(https://source.unsplash.com/" +
backgroundImageRes +
"/?" +
cityName +
")";
}
function updateTemperatureData(currentWeatherData) {
let { temp, feels_like } = currentWeatherData;
currTemperatureElement.innerText = Math.round(temp);
feelTemperatureElement.innerText = Math.round(feels_like);
}
function updateGeneralWeatherInfo(currentWeatherData) {
let generalWeatherInfo = currentWeatherData.weather[0];
let generalWeatherDescription = generalWeatherInfo["description"];
generalWeatherDescription = capitalizeFirstLetter(
generalWeatherDescription
);
generalWeatherIconElement.innerHTML =
OPEN_WEATHER_API_ICONS_TO_WU_ICONS[generalWeatherInfo["icon"]];
generalWeatherTextElement.innerText = generalWeatherDescription;
}
function updateAdditionalWeatherInfo(currentWeatherData) {
let { humidity, pressure, wind_speed, wind_deg } = currentWeatherData;
let wind_dir;
pressure = convertPressureToMMHg(pressure);
wind_dir = convertWindDirectionDegreesToCardinals(wind_deg);
pressureElement.innerText = `${pressure} mm Hg`;
humidityElement.innerText = `${humidity}%`;
windElement.innerText = `${wind_speed}m/s ${wind_dir}`;
}
function convertPressureToMMHg(pressure) {
return Math.round(pressure * hPA_TO_mm_Hg_CONVERSION_RATE);
}
function convertWindDirectionDegreesToText(windDirection) {
return WIND_DIRECTION_TEXT[(windDirection / 22.5).toFixed(0)];
}
function convertWindDirectionDegreesToCardinals(windDirection) {
return WIND_CARDINAL_DIRECTIONS[Math.round(windDirection / 45) % 8];
}
function capitalizeFirstLetter(string) {
return string
.toLowerCase()
.split(" ")
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(" ");
}