-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.ts
423 lines (359 loc) · 12.9 KB
/
script.ts
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
"use strict";
// Variables
const inputLocation = document.getElementById("location") as HTMLInputElement;
const locateButton = document.getElementById("locate");
let currentLocation: HTMLElement | null = document.querySelector(
".app__weather__widget__location"
);
const currentWeatherDetails = document.querySelector(".app__weather__details");
const appWeek: HTMLElement | null = document.querySelector(
".app__weather__week"
);
const celsius: string = "℃";
let locationPoint: string = "";
const geoapifyApiKey: string = "2e680da3a08c43bc875800cd7c1bc017";
document.addEventListener("DOMContentLoaded", function () {
let bgImage = new Image();
bgImage.src = "./images/default.jpeg";
bgImage.onload = function (): void {
document.body.style.backgroundImage = "url(" + bgImage.src + ")";
};
});
//Getting city name from input
function handleLocationInput(): void {
locationPoint = inputLocation.value.toLocaleString();
getLocation(locationPoint);
}
// Add event listener for clicking the locateButton
locateButton?.addEventListener("click", handleLocationInput);
// Add event listener for pressing the "Enter" key in the inputLocation field
inputLocation?.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
handleLocationInput();
}
});
// Fetching coordinates
async function getLocation(location: string): Promise<void> {
try {
const response = await fetch(
`https://api.geoapify.com/v1/geocode/search?text=${location}&apiKey=${geoapifyApiKey}`
);
const data = await response.json();
const resulstArr = [data.features[0].properties];
let city = data.query.parsed.city;
resulstArr.map((item) => {
let locationLatitulde = item.lat;
let locationLongitude = item.lon;
console.log(city) + "???!!!!";
getWeatherData(locationLatitulde, locationLongitude, city);
});
} catch (error) {
console.error("Error", error);
}
}
//Get geolocation and rest data
function getCity(latitude: number, longitude: number): any {
const url = `https://api.geoapify.com/v1/geocode/reverse?lat=${latitude}&lon=${longitude}&apiKey=${geoapifyApiKey}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const result = data;
// const city = result.features[0].properties.city;
currentLocation.textContent = result.features[0].properties.city;
// if (city !== undefined && city !== null) {
// currentLocation.innerHTML = city;
// console.log(city + "____!!!!!______");
// console.log(currentLocation.textContent + "<--!!!textContent!!!");
// } else {
// return;
// }
})
.catch((error) => {
console.log("error", error);
});
}
// Input allow only English characters
function validateEnglishInput(inputElement: HTMLInputElement): any {
const inputValue = inputElement.value;
const englishLetters = /^[A-Za-z\s\-]*$/;
if (!englishLetters.test(inputValue)) {
inputElement.value = inputValue.replace(/[^A-Za-z\s\-]/g, "");
}
}
// Using API to fetch weather data
async function getWeatherData(
latitude: number,
longitude: number,
city?: string
): Promise<void> {
const url = `https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${latitude}%2C%20${longitude}?unitGroup=metric&include=current%2Cdays&key=EDHKHG9ZLTHQH4GDGL22UFT76&contentType=json`;
await fetch(url)
.then((response) => response.json())
.then((data) => {
changeBackground(data.days[0].icon);
setUpInterface(data, city);
})
.catch((error) => console.error(error))
.finally(() => {
switchVisibility();
});
}
// Checking if geolocation is allowed
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(getCoordinates, errorCallback);
} else {
console.log("Geolocation is not supported by this browser.");
}
// Closing overlay if geolocation is not allowed
function errorCallback(error: GeolocationPositionError): void {
console.log("Error getting location: " + error.message);
switchVisibility();
}
function getCoordinates(position: GeolocationPosition | undefined): any {
if (position && position.coords) {
getWeatherData(position.coords.latitude, position.coords.longitude);
getCity(position.coords.latitude, position.coords.longitude);
} else {
console.log("Unable to get coordinates.");
switchVisibility();
}
}
// Creating overlay and spinner elements
const appOverlay: HTMLDivElement = document.createElement("div");
appOverlay.classList.add("app__overlay");
document.body.appendChild(appOverlay);
const appSpinner: HTMLDivElement = document.createElement("div");
appSpinner.classList.add("app__spinner");
appOverlay.appendChild(appSpinner);
// Creating app interface
function setUpInterface(weatherData: any, city: string): void {
removePreviousContent();
setCurrentDayData(weatherData, city);
setWeeksData(weatherData, city);
convertDate(weatherData.currentConditions);
}
// Removing previous data on week days
function removePreviousContent(): void {
const nodeList = document.querySelectorAll(".app__weather__week-day");
nodeList.forEach((node) => {
node.parentNode?.removeChild(node);
});
}
// Close visibility func
function switchVisibility(): void {
appOverlay.remove();
(currentWeatherDetails as HTMLElement).style.visibility = "visible";
(appWeek as HTMLElement).style.visibility = "visible";
}
// Creating week days cards and passing data
function setWeeksData(weatherData: any, city: string): void {
weatherData.days.forEach((day: any) => {
const weekDay = document.createElement("div");
weekDay.classList.add("app__weather__week-day");
let week = document.querySelector(".app__weather__week-days");
week?.appendChild(weekDay);
const weekDayHead = document.createElement("div");
weekDayHead.classList.add("app__weather__week-day__head");
weekDay.appendChild(weekDayHead);
const weekDayContent = document.createElement("div");
weekDayContent.classList.add("app__weather__week-day__content");
weekDay.appendChild(weekDayContent);
const dayIcon = document.createElement("img");
dayIcon.classList.add("app__weather__week-day__icon");
weekDayContent.appendChild(dayIcon);
dayIcon.src = `./images/${day.icon}.svg`;
const dayName = document.createElement("span");
dayName.classList.add("app__weather__week-day__name");
weekDayHead.appendChild(dayName);
dayName.innerHTML = `${convertDate(day.datetimeEpoch)}`;
const dayDate = document.createElement("span");
dayDate.classList.add("app__weather__week-day__date");
weekDayHead.appendChild(dayDate);
dayDate.innerHTML = `${day.datetime}`;
const tempCurrent = document.createElement("span");
tempCurrent.classList.add("app__weather__week-day__temp");
weekDayContent.appendChild(tempCurrent);
tempCurrent.innerHTML = `
Temperature: ${roundToClosestInt(day.temp)}${celsius}`;
const feelsLike = document.createElement("span");
feelsLike.classList.add("app__weather__week-day__feelslike");
weekDayContent.appendChild(feelsLike);
feelsLike.innerHTML = `Feels like: ${roundToClosestInt(
day.feelslike
)}${celsius}`;
const weekDayTempLimits = document.createElement("div");
weekDayTempLimits.classList.add("app__weather__week-day__temp-limits");
weekDayContent.appendChild(weekDayTempLimits);
const tempMax = document.createElement("span");
tempMax.classList.add("app__weather__week-day__max");
weekDayTempLimits.appendChild(tempMax);
tempMax.innerHTML = `Max: ${roundToClosestInt(day.tempmax)}${celsius}`;
const tempMin = document.createElement("span");
tempMin.classList.add("app__weather__week-day__min");
weekDayTempLimits.appendChild(tempMin);
tempMin.innerHTML = `Min: ${roundToClosestInt(day.tempmin)}${celsius}`;
const summary = document.createElement("span");
summary.classList.add("app__weather__week-day__description");
weekDayContent.appendChild(summary);
summary.innerHTML = `${day.description}`;
console.log(`${city} from setUpInterface`);
});
}
// Passing data to the current day fields
function setCurrentDayData(weatherData: any, city: string): void {
const currentDateElement = document.querySelector(
".app__weather__details-head__date"
);
if (currentDateElement) {
currentDateElement.innerHTML = ` ${dateFormatCurrentDay(
weatherData.days[0]?.datetimeEpoch ?? 0
)}`;
}
const currentDayName = document.querySelector(
".app__weather__details-head__title"
);
if (currentDayName) {
currentDayName.innerHTML = `${convertDate(
weatherData.days[0]?.datetimeEpoch ?? 0
)},`;
}
const currentTemperature = document.querySelector(
".app__weather__details-properties__value--temp"
);
if (currentTemperature) {
currentTemperature.innerHTML = `${roundToClosestInt(
weatherData.days[0]?.temp
)}${celsius}`;
}
const maxTemperature = document.querySelector(
".app__weather__details-properties__value--tempmax"
);
if (maxTemperature) {
maxTemperature.innerHTML = `${roundToClosestInt(
weatherData.days[0]?.tempmax
)}${celsius}`;
}
const minTemperature = document.querySelector(
".app__weather__details-properties__value--tempmin"
);
if (minTemperature) {
minTemperature.innerHTML = `${roundToClosestInt(
weatherData.days[0]?.tempmin
)}${celsius}`;
}
const currentFeelslike = document.querySelector(
".app__weather__details-properties__value--feelslike"
);
if (currentFeelslike) {
currentFeelslike.innerHTML = `${roundToClosestInt(
weatherData.days[0]?.feelslike
)}${celsius}`;
}
let currentHumidity = document.querySelector(
".app__weather__details-properties__value--humidity"
);
if (currentHumidity) {
currentHumidity.innerHTML = `${roundToClosestInt(
weatherData.days[0]?.humidity
)} %`;
}
const currentPressure = document.querySelector(
".app__weather__details-properties__value--pressure"
);
if (currentPressure) {
currentPressure.innerHTML = `${weatherData.days[0]?.pressure}`;
}
const currentSunrise = document.querySelector(
".app__weather__details-properties__value--sunrise"
);
if (currentSunrise) {
currentSunrise.innerHTML = `${weatherData.days[0]?.sunrise}`;
}
const currentSunset = document.querySelector(
".app__weather__details-properties__value--sunset"
);
if (currentSunset) {
currentSunset.innerHTML = `${weatherData.days[0]?.sunset}`;
}
let currentDayIcon = document.querySelector(".app__weather__widget__icon");
currentDayIcon?.setAttribute(
"src",
`./images/${weatherData.days[0].icon}.svg`
);
const currentDayConditions = document.querySelector(
".app__weather__widget__conditions"
);
if (currentDayConditions) {
currentDayConditions.innerHTML = `${weatherData.days[0]?.description}`;
}
currentLocation = document.querySelector(".app__weather__widget__location");
if (currentLocation?.textContent) {
currentLocation.textContent = city;
}
}
// Changing background according to the weather
function changeBackground(icon: string): void {
switch (icon) {
case "rain":
case "showers-day":
case "showers-night":
case "thunder-rain":
case "thunder-showers-day":
case "thunder-showers-night":
document.body.style.backgroundImage = 'url("./images/rainy.jpg")';
break;
case "clear-day":
case "clear-night":
document.body.style.backgroundImage = 'url("./images/clear.jpg")';
break;
case "fog":
document.body.style.backgroundImage = 'url("./images/foggy.jpeg")';
break;
case "snow-showers-day":
case "snow-showers-night":
case "snow":
document.body.style.backgroundImage = 'url("./images/snowy.jpeg")';
break;
default:
document.body.style.backgroundImage = 'url("./images/default.jpeg")';
break;
}
}
// To convert epochSeconds to the day of the week name
function convertDate(epochSeconds: number): string {
const date = new Date(epochSeconds * 1000);
const daysOfWeek = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const dayOfWeek = daysOfWeek[date.getDay()];
return dayOfWeek;
}
// Formatting date for the current day section
function dateFormatCurrentDay(currentDayEpochSeconds: number): string {
const date = new Date(currentDayEpochSeconds * 1000);
const formattedDate = date.toLocaleDateString("en-US", {
month: "long",
day: "numeric",
});
return formattedDate;
}
// Rounding function, for rounding value to the closest integer
function roundToClosestInt(value: number): number {
return Math.round(value);
}
// Creating digital clock
(function () {
let currentTime = new Date();
let hours: number | string = currentTime.getHours();
let minutes: number | string = currentTime.getMinutes();
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
let timeString = hours + ":" + minutes;
document.getElementById("clock")!.innerHTML = timeString;
})();