-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
618 lines (583 loc) · 16.6 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// const options = {
// method: 'GET',
// headers: {
// 'X-RapidAPI-Key': '77a45e249cmsh792cd7445b30ea1p146476jsna8123226ed35',
// 'X-RapidAPI-Host': 'weather-by-api-ninjas.p.rapidapi.com'
// }
// };
// fetch('https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?units=metric&q=Delhi', options)
// .then(response => response.json())
// .then(response => console.log(response))
// .then(err => console.error(err));
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 = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
// 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 in our database");
});
}
//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 "https://i.ibb.co/PZQXH8V/27.png";
} else if (condition === "partly-cloudy-night") {
return "https://i.ibb.co/Kzkk59k/15.png";
} else if (condition === "rain") {
return "https://i.ibb.co/kBd2NTS/39.png";
} else if (condition === "clear-day") {
return "https://i.ibb.co/rb4rrJL/26.png";
} else if (condition === "clear-night") {
return "https://i.ibb.co/1nxNGHL/10.png";
} else {
return "https://i.ibb.co/rb4rrJL/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 = "https://i.ibb.co/qNv7NxZ/pc.webp";
} else if (condition === "partly-cloudy-night") {
bg = "https://i.ibb.co/RDfPqXz/pcn.jpg";
} else if (condition === "rain") {
bg = "https://i.ibb.co/h2p6Yhd/rain.webp";
} else if (condition === "clear-day") {
bg = "https://i.ibb.co/WGry01m/cd.jpg";
} else if (condition === "clear-night") {
bg = "https://i.ibb.co/kqtZ1Gx/cn.jpg";
} else {
bg = "https://i.ibb.co/qNv7NxZ/pc.webp";
}
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 = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
return days[day.getDay()];
}
// function to get uv index status
function measureUvIndex(uvIndex) {
if (uvIndex <= 2) {
uvText.innerText = "Low";
} else if (uvIndex <= 5) {
uvText.innerText = "Moderate";
} else if (uvIndex <= 7) {
uvText.innerText = "High";
} else if (uvIndex <= 10) {
uvText.innerText = "Very High";
} else {
uvText.innerText = "Extreme";
}
}
// function to get humidity status
function updateHumidityStatus(humidity) {
if (humidity <= 30) {
humidityStatus.innerText = "Low";
} else if (humidity <= 60) {
humidityStatus.innerText = "Moderate";
} else {
humidityStatus.innerText = "High";
}
}
// function to get visibility status
function updateVisibiltyStatus(visibility) {
if (visibility <= 0.03) {
visibilityStatus.innerText = "Dense Fog";
} else if (visibility <= 0.16) {
visibilityStatus.innerText = "Moderate Fog";
} else if (visibility <= 0.35) {
visibilityStatus.innerText = "Light Fog";
} else if (visibility <= 1.13) {
visibilityStatus.innerText = "Very Light Fog";
} else if (visibility <= 2.16) {
visibilityStatus.innerText = "Light Mist";
} else if (visibility <= 5.4) {
visibilityStatus.innerText = "Very Light Mist";
} else if (visibility <= 10.8) {
visibilityStatus.innerText = "Clear Air";
} else {
visibilityStatus.innerText = "Very Clear Air";
}
}
// function to get air quality status
function updateAirQualityStatus(airquality) {
if (airquality <= 50) {
airQualityStatus.innerText = "Good👌";
} else if (airquality <= 100) {
airQualityStatus.innerText = "Moderate😐";
} else if (airquality <= 150) {
airQualityStatus.innerText = "Unhealthy for Sensitive Groups😷";
} else if (airquality <= 200) {
airQualityStatus.innerText = "Unhealthy😷";
} else if (airquality <= 250) {
airQualityStatus.innerText = "Very Unhealthy😨";
} else {
airQualityStatus.innerText = "Hazardous😱";
}
}
// 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);
}
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);
}
}
// Cities add your own to get in search
cities = [
{
country: "in",
name: "Delhi",
lat: "28.679079",
lng: "77.069710",
},
{
country: "in",
name: "New Delhi",
lat: "28.6139",
lng: "77.2090",
},
{
country: "in",
name: "Agra",
lat: "27.17042035",
lng: "78.01502071",
},
{
country: "in",
name: "Aligarh",
lat: "27.89221092",
lng: "78.06178788",
},
{
country: "in",
name: "Lucknow",
lat: "30.67791",
lng: "71.74344",
},
{
country: "in",
name: "Allahabad",
lat: "25.45499534",
lng: "81.84000688",
},
{
country: "in",
name: "Bareilly",
lat: "28.34538739",
lng: "79.41999955",
},
{
country: "in",
name: "Budaun",
lat: "28.03000612",
lng: "79.08999385",
},
{
country: "in",
name: "Bulandshahr",
lat: "28.4103705",
lng: "77.84841589",
},
{
country: "in",
name: "Etawah",
lat: "26.78545677",
lng: "79.01495968",
},
{
country: "in",
name: "Faizabad",
lat: "26.75039431",
lng: "82.17001257",
},
{
country: "in",
name: "Fatehpur",
lat: "25.88036989",
lng: "80.80001868",
},
{
country: "in",
name: "Farrukhabad",
lat: "27.387049",
lng: "79.588127",
},
{
country: "in",
name: "Ghaziabad",
lat: "28.66038108",
lng: "77.40839107",
},
{
country: "in",
name: "Gorakhpu",
lat: "26.75039431",
lng: "83.38001623",
},
{
country: "in",
name: "jaipur",
lat: "26.922070",
lng: "75.778885",
},
{
country: "in",
name: "Jodhpur",
lat: "26.223370",
lng: "72.998917",
},
{
country: "in",
name: "Udaipur",
lat: "24.571270",
lng: "73.691544",
},
{
country: "in",
name: "Jaisalmer",
lat: "26.9157",
lng: "70.9083",
},
{
country: "in",
name: "Patna",
lat: "25.5941",
lng: "85.1376",
},
{
country: "in",
name: "Kanpur",
lat: "26.4499",
lng: "80.3319",
},
{
country: "in",
name: "Kolkata",
lat: "22.5726",
lng: "88.363892",
},
{
country: "in",
name: "Mumbai",
lat: "19.076090",
lng: "72.877426",
},
];