-
Notifications
You must be signed in to change notification settings - Fork 2
/
newScript.js
724 lines (597 loc) · 19.6 KB
/
newScript.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
var myInit = {
method: 'GET',
mode: 'cors',
cache: 'default'
};
function defLoc(lat, lon, unit = "metric", theme = "light") {
var mainReq = new Request('https://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=' + unit + '&appid=4595fa54578e530eb98a555b672f6185', myInit);
fetch(mainReq).then(function (response) {
return response.json();
}).then(function (myJson) {
loc = myJson.name;
console.log(loc);
pFormat(myJson);
currentLocs.children[0].remove();
addSuccess(myJson.name);
lstore();
});
var graphReq = new Request('https://api.openweathermap.org/data/2.5/forecast/daily?units=' + unit + '&lat=' + lat + '&lon=' + lon + '&appid=4595fa54578e530eb98a555b672f6185&cnt=7', myInit);
fetch(graphReq).then(function (gresponse) {
return gresponse.json();
}).then(function (graph) {
plot(graph);
});
if (theme == "dark") {
removeClass(document.getElementById('light').nextElementSibling, 'checked');
addClass(document.getElementById('dark').nextElementSibling, 'checked');
}
themer()
};
var unit = "metric";
// React to theme radio button
var root = document.querySelector(':root');
function themer() {
if (document.getElementsByName("theme")[1].checked) {
//dark
root.style.setProperty('--body', '#3d3d3dd1');
root.style.setProperty('--widget', '#06b87c');
root.style.setProperty('--highlight', '#f3f3f3');
root.style.setProperty('--theme', '#00acc1');
root.style.setProperty('--selected', '#2b2b2b');
root.style.setProperty('--base', '#3d3d3d');
root.style.setProperty('--text', '#ececec');
root.style.setProperty('--listtext', '#bfbfbf');
root.style.setProperty('--elevation', '#ffffff14');
Chart.defaults.global.defaultFontColor = '#ececec';
} else {
//light - default
root.style.setProperty('--body', '#efefef');
root.style.setProperty('--widget', '#52a3db');
root.style.setProperty('--highlight', '#424242');
root.style.setProperty('--theme', '#4fa584');
root.style.setProperty('--selected', '#ededeb');
root.style.setProperty('--base', '#fafafa');
root.style.setProperty('--text', '#585858');
root.style.setProperty('--listtext', '#757575');
root.style.setProperty('--elevation', '#ededeb66');
Chart.defaults.global.defaultFontColor = '#585858';
}
sstore();
}
addClass(document.querySelectorAll('.location-link')[0], "z-depth-1-half");
document.querySelectorAll('.location-link')[0].style.setProperty('background-color', 'var(--elevation)')
var f = 0;
var p = 0;
function locFormat(loc) {
loc = loc;
dataFormat();
f = 1;
}
// react to units radio button
function dataFormat() {
if (document.getElementsByName("tempunit")[0].checked) {
unit = "metric";
} else {
unit = "imperial";
}
loading();
cload();
document.getElementById("location").innerHTML = "Weather Forecast";
root.style.setProperty('--bg1', '#2F80ED');
root.style.setProperty('--bg2', '#56CCF2');
var mainReq = new Request("https://api.openweathermap.org/data/2.5/weather?q=" + loc + "&units=" + unit + "&appid=4595fa54578e530eb98a555b672f6185", myInit);
fetch(mainReq).then(function (response) {
if (response.ok) {
return response;
}
throw Error(response.statusText);
}).then(function (response) {
return response.json();
}).then(function (json) {
pFormat(json);
}).catch(function (error) {
console.log('Request failed:', error.message);
M.toast({
html: 'Location not found'
});
hideLoader();
});
var graphReq = new Request("https://api.openweathermap.org/data/2.5/forecast/daily?units=" + unit + "&q=" + loc + "&appid=4595fa54578e530eb98a555b672f6185&cnt=7", myInit);
fetch(graphReq).then(function (gresponse) {
if (gresponse.ok) {
return gresponse;
}
throw Error(gresponse.statusText);
}).then(function (gresponse) {
return gresponse.json();
}).then(function (json) {
plot(json);
}).catch(function (error) {
console.log('Request failed:', error.message);
hidecLoad();
});
};
var locList = document.querySelectorAll('.location-link');
locList.forEach(function (locationList) {
locationList.addEventListener('click', function (e) {
loc = e.target.getAttribute("place");
if (loc != null) {
locFormat(loc);
locList.forEach(function (locList) {
removeClass(locList, "z-depth-1-half");
locList.style.setProperty('background-color', 'transparent')
});
addClass(locationList, "z-depth-1-half");
locationList.style.setProperty('background-color', 'var(--elevation)')
}
})
locationList.querySelector('i').addEventListener('click', function (c) {
c.target.parentNode.remove(0);
//document.querySelector('.page-content').innerHTML = "<h1>Click on a location or add a new location to view Weather Info.</h1>"
});
});
// main function
function pFormat(weatherData) {
// Units Definition
if (unit == "metric") {
tu = "°C";
su = "m/s";
} else {
tu = "°F";
su = "Mph";
}
if (p == 1) {
addSuccess(weatherData.name);
}
hideLoader();
document.getElementById("location").innerHTML = weatherData.name + " Forecast";
document.getElementById("country").innerHTML = weatherData.name + ", " + weatherData.sys.country;
document.getElementById("title").innerHTML = "<b>" + weatherData.weather[0].main + "</b>";
document.getElementById("desc").innerHTML = weatherData.weather[0].description.toUpperCase();
document.getElementById("temp").innerHTML = weatherData.main.temp.toFixed(0) + tu;
document.getElementById("mainIcon").setAttribute("class", "wi wi-owm-" + weatherData.weather[0].id);
document.getElementById("humid").innerHTML = weatherData.main.humidity + "%";
document.getElementById("humidBar").style.width = weatherData.main.humidity + "%";
document.getElementById("wind").innerHTML = weatherData.wind.speed.toFixed(1) + " <h6 style=\"float: right\">" + su + "</h6>";
//document.getElementById("windDir").setAttribute("class", "wi wi-wind towards-" + weatherData.wind.deg.toFixed(0) + "-deg");
//document.getElementById("pressure").innerHTML = weatherData.main.pressure.toFixed(1) + " <h6 style=\"float: right\">hPa</h6>";
document.getElementById("cloudCover").innerHTML = weatherData.clouds.all + "%";
document.getElementById("cloudBar").style.width = weatherData.clouds.all + "%";
//Set Gradient
gradient(weatherData.weather[0].id);
//Sunrise & Sunset
sr = new Date(weatherData.sys.sunrise * 1000);
srf = tmFrmt(sr.getHours()) + ":" + tmFrmt(sr.getMinutes());
document.getElementById("sr").innerHTML = "Sunrise: " + srf;
ss = new Date(weatherData.sys.sunset * 1000);
ssf = tmFrmt(ss.getHours()) + ":" + tmFrmt(ss.getMinutes());
document.getElementById("ss").innerHTML = "Sunset: " + ssf;
//date widget
var ts = weatherData.dt;
var date = new Date(ts * 1000);
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var months = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("time").innerHTML = tmFrmt(date.getHours()) + ":" + tmFrmt(date.getMinutes());
document.getElementById("wday").innerHTML = days[date.getDay()].toUpperCase();
document.getElementById("mdate").innerHTML = date.getDate();
document.getElementById("month").innerHTML = months[date.getMonth()];
document.getElementById("year").innerHTML = date.getFullYear();
//Flags
p = 0;
console.log(weatherData);
if (f == 1) {
lstore();
}
sstore();
}
// Graphing Functions
function plot(graphData) {
document.getElementById("cloud-chart-container").innerHTML = '<canvas id="cloudCanvas"></canvas>';
document.getElementById("chart-container").innerHTML = '<canvas id="canvas"></canvas>';
console.log(graphData);
hidecLoad();
var maxTempArray = new Array();
for (let i = 0; i <= 6; i++) {
maxTempArray.push(graphData.list[i].temp.max);
};
var minTempArray = new Array();
for (let i = 0; i <= 6; i++) {
minTempArray.push(graphData.list[i].temp.min);
};
var dayArray = new Array();
for (let i = 0; i <= 6; i++) {
var timestamp = graphData.list[i].dt;
var date = new Date(timestamp * 1000);
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
dayArray.push(days[date.getDay()]);
};
var dateArray = new Array();
for (let i = 0; i <= 6; i++) {
var timestamp = graphData.list[i].dt;
var date = new Date(timestamp * 1000);
dateArray.push(date.getDate());
};
var ccArray = new Array();
for (let i = 0; i <= 6; i++) {
ccArray.push(graphData.list[i].clouds);
};
var config = {
type: 'line',
data: {
labels: dayArray,
datasets: [{
label: 'Max Temp',
backgroundColor: 'rgba(77, 182, 172, 1)',
borderColor: 'rgba(77, 182, 172, 1)',
data: maxTempArray,
fill: false,
lineTension: 0,
}, {
label: 'Min Temp',
fill: false,
backgroundColor: 'rgba(79, 195, 247, 1)',
borderColor: 'rgba(79, 195, 247, 1)',
data: minTempArray,
lineTension: 0,
}]
},
options: {
maintainAspectRatio: false,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: ''
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Temperature'
}
}]
}
}
};
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
// Cloud chart
var cloudConfig = {
type: 'line',
data: {
labels: dateArray,
datasets: [{
label: 'Cloud cover',
backgroundColor: 'rgba(251, 140, 0, 1)',
borderColor: 'rgba(251, 140, 0, 1)',
data: ccArray,
fill: false,
}]
},
options: {
maintainAspectRatio: false,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Percentage'
}
}]
}
}
};
var cld = document.getElementById('cloudCanvas').getContext('2d');
window.myLine = new Chart(cld, cloudConfig);
};
//Gradient Function
function gradient(wc) {
var bg1, bg2, wc;
if (wc >= 200 & wc < 300) {
bg2 = '#859398';
bg1 = '#360033';
} else if (wc >= 300 & wc < 400) {
bg2 = '#26a0da';
bg1 = '#314755';
} else if (wc >= 500 & wc < 600) {
bg2 = '#4b6cb7';
bg1 = '#182848';
} else if (wc >= 600 & wc < 700) {
bg2 = '#076585';
bg1 = '#fff';
} else if (wc >= 700 & wc < 800) {
bg2 = '#2c3e50';
bg1 = '#bdc3c7';
} else if (wc > 800 & wc < 900) {
bg2 = '#8e9eab';
bg1 = '#2F80ED';
} else {
bg2 = '#56CCF2';
bg1 = '#2F80ED';
}
root.style.setProperty('--bg1', bg1);
root.style.setProperty('--bg2', bg2);
}
//Refresh Button
document.getElementById('refresh').addEventListener('click', function () {
locFormat(loc);
});
// add location
document.getElementById('fab').addEventListener('click', function (e) {
loc = document.getElementById('addLocation').value;
console.log(loc);
p = 1;
locFormat(loc);
//Fab animations
toggleClass(document.getElementById('addLocation'), 'valid');
removeClass(document.getElementById('addLocation').nextElementSibling, 'active');
document.getElementById('addLocation').value = "";
toggle();
});
window.addEventListener('keydown', function (e) {
if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
e.preventDefault();
return false;
}
}
}, true);
document.getElementById('addLocation').addEventListener('keyup', function (e) {
if (e.keyCode === 13) {
loc = document.getElementById('addLocation').value;
console.log(loc);
p = 1;
locFormat(loc);
//Fab animations
toggleClass(document.getElementById('addLocation'), 'valid');
removeClass(document.getElementById('addLocation').nextElementSibling, 'active');
document.getElementById('addLocation').value = "";
toggle();
}
}, false);
//Location added
function addSuccess(nm) {
var locNode = document.getElementById('locationList');
var newItem = document.createElement("a");
var close = document.createElement('i');
//adding new location
var newLocName = document.createTextNode(nm.toProperCase());
newItem.appendChild(newLocName);
locNode.insertBefore(newItem, locNode.childNodes[0]);
addClass(locNode.childNodes[0], "mdl-navigation__link location-link");
var attr = document.createAttribute("place");
attr.value = nm;
locNode.childNodes[0].setAttributeNode(attr);
//adding the close button
newItem.appendChild(close);
addClass(locNode.childNodes[0].querySelector('i'), "material-icons");
locNode.childNodes[0].querySelector('i').appendChild(document.createTextNode("close"));
locList = document.querySelectorAll('.location-link');
locList.forEach(function (locList) {
removeClass(locList, "z-depth-1-half");
locList.style.setProperty('background-color', 'transparent')
});
addClass(locNode.childNodes[0], "z-depth-1-half");
locNode.childNodes[0].style.setProperty('background-color', 'var(--elevation)')
locNode.childNodes[0].addEventListener('click', function (e) {
loc = e.target.getAttribute("place");
if (loc != null) {
locFormat(loc);
locList.forEach(function (locList) {
removeClass(locList, "z-depth-1-half");
locList.style.setProperty('background-color', 'transparent')
});
addClass(e.target, "z-depth-1-half");
e.target.style.setProperty('background-color', 'var(--elevation)')
}
})
locNode.childNodes[0].querySelector('i').addEventListener('click', async (c) => {
await c.target.parentNode.remove(0);
lstore();
});
}
var currentLocs = document.getElementById('locationList');
var mobLoc = document.getElementById('mobileLocation');
function populateLocs(x) {
if (x.matches) { // If media query matches
mobLoc.appendChild(currentLocs);
} else {
document.getElementById('rightNav').appendChild(currentLocs);
}
};
var x = window.matchMedia("(max-width: 720px)");
populateLocs(x);
x.addListener(populateLocs);
// toggle class functions
function hasClass(elem, className) {
return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}
function addClass(elem, className) {
if (!hasClass(elem, className)) {
elem.className += ' ' + className;
}
}
function removeClass(elem, className) {
var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' ';
if (hasClass(elem, className)) {
while (newClass.indexOf(' ' + className + ' ') >= 0) {
newClass = newClass.replace(' ' + className + ' ', ' ');
}
elem.className = newClass.replace(/^\s+|\s+$/g, '');
}
}
function toggleClass(elem, className) {
var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' ';
if (hasClass(elem, className)) {
while (newClass.indexOf(' ' + className + ' ') >= 0) {
newClass = newClass.replace(' ' + className + ' ', ' ');
}
elem.className = newClass.replace(/^\s+|\s+$/g, '');
} else {
elem.className += ' ' + className;
}
}
function toggle() {
toggleClass(document.getElementById("fab"), 'scale-out');
}
document.getElementById("addLocation").addEventListener('focusin', function () {
if (document.getElementById('addLocation').value == "") {
toggle();
}
});
document.getElementById("addLocation").addEventListener('focusout', function () {
if (document.getElementById('addLocation').value == "") {
toggle();
}
});
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
///////////////////////////////// Time Formatter ///////////////////////////////
function tmFrmt(n) {
if (n < 10) {
n = "0" + n.toString()
} else {
n = n;
}
return n;
}
///////////////////////////////// Preloaders ///////////////////////////////////
function loading() {
removeClass(document.getElementById("loader"), 'hide');
addClass(document.getElementById("content"), 'hide');
addClass(document.getElementById("mainIcon"), 'hide');
addClass(document.getElementById("temp"), 'hide');
};
function hideLoader() {
addClass(document.getElementById("loader"), 'hide');
removeClass(document.getElementById("content"), 'hide');
removeClass(document.getElementById("mainIcon"), 'hide');
removeClass(document.getElementById("temp"), 'hide');
};
function cload() {
removeClass(document.getElementById("cload"), 'hide');
addClass(document.getElementById("graph"), 'hide');
};
function hidecLoad() {
addClass(document.getElementById("cload"), 'hide');
removeClass(document.getElementById("graph"), 'hide');
};
///////////////////////////// GeoLocation //////////////////////////////
function getLoc() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPos, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
};
function showPos(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
M.toast({
html: "Latitude: " + lat + "<br>Longitude: " + lon
});
defLoc(lat, lon);
};
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
M.toast({
html: "User denied the request for Geolocation."
});
break;
case error.POSITION_UNAVAILABLE:
M.toast({
html: "Location information is unavailable."
});
break;
case error.TIMEOUT:
M.toast({
html: "The request to get user location timed out."
});
break;
case error.UNKNOWN_ERROR:
M.toast({
html: "An unknown error occurred."
});
break;
}
};
/////////////////////////// LocalStorage /////////////////////////////
function lstore() {
if (typeof (Storage) !== "undefined") {
var lsLocs = [];
var i;
avlLoc = document.querySelectorAll('.location-link');
localStorage.removeItem("locations");
for (i = 0; i < avlLoc.length; i++) {
lsLocs[i] = avlLoc[i].getAttribute("place");
};
localStorage.setItem("locations", JSON.stringify(lsLocs));
} else {
console.log("Sorry! No localStorage support");
};
}
function sstore() {
if (typeof (Storage) !== "undefined") {
var thm;
if (document.getElementsByName("theme")[1].checked) {
thm = "dark"
} else {
thm = "light"
}
localStorage.removeItem("theme");
localStorage.setItem("theme", thm);
localStorage.removeItem("unit");
localStorage.setItem("unit", unit);
console.log(unit);
}
}
if (typeof (Storage) !== "undefined") {
if (localStorage.length != 0) {
var locStore = JSON.parse(localStorage.getItem("locations"));
if (locStore.length != 0) {
console.log("Data Found");
console.log(locStore);
currentLocs.children[0].remove();
for (i = locStore.length - 1; i >= 0; i--) {
addSuccess(locStore[i]);
};
loc = document.querySelectorAll('.location-link')[0].getAttribute("place");
locFormat(locStore[0]);
} else {
getLoc();
};
} else {
getLoc();
};
} else {
defLoc(22.57, 88.36);
}