-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
463 lines (433 loc) · 13.3 KB
/
script.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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
const temp = document.getElementById("temp"),
date = document.getElementById("date-time"),
condition = document.getElementById("condition"),
rain = document.getElementById("rain"),
mainIcon = document.getElementById("icon"),
currentLocation = document.getElementById("location"),
uvIndex = document.querySelector(".uv-index"),
uvText = document.querySelector(".uv-text"),
windSpeed = document.querySelector(".wind-speed"),
sunRise = document.querySelector(".sun-rise"),
sunSet = document.querySelector(".sun-set"),
humidity = document.querySelector(".humidity"),
visibilty = document.querySelector(".visibilty"),
humidityStatus = document.querySelector(".humidity-status"),
airQuality = document.querySelector(".air-quality"),
airQualityStatus = document.querySelector(".air-quality-status"),
visibilityStatus = document.querySelector(".visibilty-status"),
searchForm = document.querySelector("#search"),
search = document.querySelector("#query"),
celciusBtn = document.querySelector(".celcius"),
fahrenheitBtn = document.querySelector(".fahrenheit"),
tempUnit = document.querySelectorAll(".temp-unit"),
hourlyBtn = document.querySelector(".hourly"),
weekBtn = document.querySelector(".week"),
weatherCards = document.querySelector("#weather-cards");
let currentCity = "";
let currentUnit = "c";
let hourlyorWeek = "week";
// function to get date and time
function getDateTime() {
let now = new Date(),
hour = now.getHours(),
minute = now.getMinutes();
let days = [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
];
// 12 hours format
hour = hour % 12;
if (hour < 10) {
hour = "0" + hour;
}
if (minute < 10) {
minute = "0" + minute;
}
let dayString = days[now.getDay()];
return `${dayString}, ${hour}:${minute}`;
}
//Updating date and time
date.innerText = getDateTime();
setInterval(() => {
date.innerText = getDateTime();
}, 1000);
// function to get public ip address
function getPublicIp() {
fetch("https://geolocation-db.com/json/", {
method: "GET",
headers: {},
})
.then((response) => response.json())
.then((data) => {
currentCity = data.city;
getWeatherData(data.city, currentUnit, hourlyorWeek);
})
.catch((err) => {
console.error(err);
});
}
getPublicIp();
// function to get weather data
function getWeatherData(city, unit, hourlyorWeek) {
fetch(
`https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${city}?unitGroup=metric&key=EJ6UBL2JEQGYB3AA4ENASN62J&contentType=json`,
{
method: "GET",
headers: {},
}
)
.then((response) => response.json())
.then((data) => {
let today = data.currentConditions;
if (unit === "c") {
temp.innerText = today.temp;
} else {
temp.innerText = celciusToFahrenheit(today.temp);
}
currentLocation.innerText = data.resolvedAddress;
condition.innerText = today.conditions;
rain.innerText = "Perc - " + today.precip + "%";
uvIndex.innerText = today.uvindex;
windSpeed.innerText = today.windspeed;
measureUvIndex(today.uvindex);
mainIcon.src = getIcon(today.icon);
changeBackground(today.icon);
humidity.innerText = today.humidity + "%";
updateHumidityStatus(today.humidity);
visibilty.innerText = today.visibility;
updateVisibiltyStatus(today.visibility);
airQuality.innerText = today.winddir;
updateAirQualityStatus(today.winddir);
if (hourlyorWeek === "hourly") {
updateForecast(data.days[0].hours, unit, "day");
} else {
updateForecast(data.days, unit, "week");
}
sunRise.innerText = covertTimeTo12HourFormat(today.sunrise);
sunSet.innerText = covertTimeTo12HourFormat(today.sunset);
})
.catch((err) => {
alert("City not found");
});
}
//function to update Forecast
function updateForecast(data, unit, type) {
weatherCards.innerHTML = "";
let day = 0;
let numCards = 0;
if (type === "day") {
numCards = 24;
} else {
numCards = 7;
}
for (let i = 0; i < numCards; i++) {
let card = document.createElement("div");
card.classList.add("card");
let dayName = getHour(data[day].datetime);
if (type === "week") {
dayName = getDayName(data[day].datetime);
}
let dayTemp = data[day].temp;
if (unit === "f") {
dayTemp = celciusToFahrenheit(data[day].temp);
}
let iconCondition = data[day].icon;
let iconSrc = getIcon(iconCondition);
let tempUnit = "°C";
if (unit === "f") {
tempUnit = "°F";
}
card.innerHTML = `
<h2 class="day-name">${dayName}</h2>
<div class="card-icon">
<img src="${iconSrc}" class="day-icon" alt="" />
</div>
<div class="day-temp">
<h2 class="temp">${dayTemp}</h2>
<span class="temp-unit">${tempUnit}</span>
</div>
`;
weatherCards.appendChild(card);
day++;
}
}
// function to change weather icons
function getIcon(condition) {
if (condition === "partly-cloudy-day") {
return "icons/sun/27.png";
} else if (condition === "partly-cloudy-night") {
return "icons/moon/15.png";
} else if (condition === "rain") {
return "icons/rain/39.png";
} else if (condition === "clear-day") {
return "icons/sun/26.png";
} else if (condition === "clear-night") {
return "icons/moon/10.png";
} else {
return "icons/sun/26.png";
}
}
// function to change background depending on weather conditions
function changeBackground(condition) {
const body = document.querySelector("body");
let bg = "";
if (condition === "partly-cloudy-day") {
bg = "images/pc.jpg";
} else if (condition === "partly-cloudy-night") {
bg = "images/pcn.jpg";
} else if (condition === "rain") {
bg = "images/rain.jpg";
} else if (condition === "clear-day") {
bg = "images/cd.jpg";
} else if (condition === "clear-night") {
bg = "images/cn.jpg";
} else {
bg = "images/pc.jpg";
}
body.style.backgroundImage = `linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ),url(${bg})`;
}
//get hours from hh:mm:ss
function getHour(time) {
let hour = time.split(":")[0];
let min = time.split(":")[1];
if (hour > 12) {
hour = hour - 12;
return `${hour}:${min} PM`;
} else {
return `${hour}:${min} AM`;
}
}
// convert time to 12 hour format
function covertTimeTo12HourFormat(time) {
let hour = time.split(":")[0];
let minute = time.split(":")[1];
let ampm = hour >= 12 ? "pm" : "am";
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
let strTime = hour + ":" + minute + " " + ampm;
return strTime;
}
// function to get day name from date
function getDayName(date) {
let day = new Date(date);
let days = [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
];
return days[day.getDay()];
}
// function to get uv index status
function measureUvIndex(uvIndex) {
if (uvIndex <= 2) {
uvText.innerText = "Leicht";
} else if (uvIndex <= 5) {
uvText.innerText = "Moderate";
} else if (uvIndex <= 7) {
uvText.innerText = "Hoch";
} else if (uvIndex <= 10) {
uvText.innerText = "Very Hoch";
} else {
uvText.innerText = "Extrem";
}
}
// function to get humidity status
function updateHumidityStatus(humidity) {
if (humidity <= 30) {
humidityStatus.innerText = "Leicht";
} else if (humidity <= 60) {
humidityStatus.innerText = "Moderat";
} else {
humidityStatus.innerText = "Hoch";
}
}
// function to get visibility status
function updateVisibiltyStatus(visibility) {
if (visibility <= 0.03) {
visibilityStatus.innerText = "Dichter Nebel";
} else if (visibility <= 0.16) {
visibilityStatus.innerText = "Moderater Nebel";
} else if (visibility <= 0.35) {
visibilityStatus.innerText = "Leichter Nebel";
} else if (visibility <= 1.13) {
visibilityStatus.innerText = "Sehr Leichter Nebel";
} else if (visibility <= 2.16) {
visibilityStatus.innerText = "Leichter Regen";
} else if (visibility <= 5.4) {
visibilityStatus.innerText = "Sehr Leichter Regen";
} else if (visibility <= 10.8) {
visibilityStatus.innerText = "Klare Luft";
} else {
visibilityStatus.innerText = "Sehr Klare Luft";
}
}
// function to get air quality status
function updateAirQualityStatus(airquality) {
if (airquality <= 50) {
airQualityStatus.innerText = "Gut👌";
} else if (airquality <= 100) {
airQualityStatus.innerText = "Moderat😐";
} else if (airquality <= 150) {
airQualityStatus.innerText = "Ungesund Für Sensitive Gruppen😷";
} else if (airquality <= 200) {
airQualityStatus.innerText = "Ungesund😷";
} else if (airquality <= 250) {
airQualityStatus.innerText = "Sehr Ungesund😨";
} else {
airQualityStatus.innerText = "Schädlich😱";
}
}
// function to handle search form
searchForm.addEventListener("submit", (e) => {
e.preventDefault();
let location = search.value;
if (location) {
currentCity = location;
getWeatherData(location, currentUnit, hourlyorWeek);
}
});
// function to conver celcius to fahrenheit
function celciusToFahrenheit(temp) {
return ((temp * 9) / 5 + 32).toFixed(1);
}
// array of cities
import cities from "./cities.js";
var currentFocus;
search.addEventListener("input", function (e) {
removeSuggestions();
var a,
b,
i,
val = this.value;
if (!val) {
return false;
}
currentFocus = -1;
a = document.createElement("ul");
a.setAttribute("id", "suggestions");
this.parentNode.appendChild(a);
for (i = 0; i < cities.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (
cities[i].name.substr(0, val.length).toUpperCase() == val.toUpperCase()
) {
/*create a li element for each matching element:*/
b = document.createElement("li");
/*make the matching letters bold:*/
b.innerHTML =
"<strong>" + cities[i].name.substr(0, val.length) + "</strong>";
b.innerHTML += cities[i].name.substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + cities[i].name + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function (e) {
/*insert the value for the autocomplete text field:*/
search.value = this.getElementsByTagName("input")[0].value;
removeSuggestions();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
search.addEventListener("keydown", function (e) {
var x = document.getElementById("suggestions");
if (x) x = x.getElementsByTagName("li");
if (e.keyCode == 40) {
/*If the arrow DOWN key
is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) {
/*If the arrow UP key
is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
}
if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = x.length - 1;
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("active");
}
}
function removeSuggestions() {
var x = document.getElementById("suggestions");
if (x) x.parentNode.removeChild(x);
}
fahrenheitBtn.addEventListener("click", () => {
changeUnit("f");
});
celciusBtn.addEventListener("click", () => {
changeUnit("c");
});
// function to change unit
function changeUnit(unit) {
if (currentUnit !== unit) {
currentUnit = unit;
tempUnit.forEach((elem) => {
elem.innerText = `°${unit.toUpperCase()}`;
});
if (unit === "c") {
celciusBtn.classList.add("active");
fahrenheitBtn.classList.remove("active");
} else {
celciusBtn.classList.remove("active");
fahrenheitBtn.classList.add("active");
}
getWeatherData(currentCity, currentUnit, hourlyorWeek);
}
}
hourlyBtn.addEventListener("click", () => {
changeTimeSpan("hourly");
});
weekBtn.addEventListener("click", () => {
changeTimeSpan("week");
});
// function to change hourly to weekly or vice versa
function changeTimeSpan(unit) {
if (hourlyorWeek !== unit) {
hourlyorWeek = unit;
if (unit === "hourly") {
hourlyBtn.classList.add("active");
weekBtn.classList.remove("active");
} else {
hourlyBtn.classList.remove("active");
weekBtn.classList.add("active");
}
getWeatherData(currentCity, currentUnit, hourlyorWeek);
}
}