-
Notifications
You must be signed in to change notification settings - Fork 0
/
radarscript.js
2154 lines (1867 loc) · 93.4 KB
/
radarscript.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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Thanks to wxtership from XWD for the light/dark theme maps code
var mapobj = document.getElementById("mapid");
var map = L.map(mapobj, { attributionControl: false, zoomControl: false, zoomSnap: 0, minZoom: 2}).setView([38.0, -100.4], 4);
// Set the max bounds
var southWest = L.latLng(-85, -180);
var northEast = L.latLng(85, 180);
var bounds = L.latLngBounds(southWest, northEast);
map.setMaxBounds(bounds);
map.on('drag', function() {
map.panInsideBounds(bounds, { animate: false });
});
var lightModeLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19
}).addTo(map);
lightModeLayer.getContainer().style.backgroundColor = 'white';
var darkModeLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19
});
var currentMapLayer = lightModeLayer;
function fadeOutElement(element) {
element = document.getElementById(element);
element.classList.add('fade-out');
setTimeout(function() {
element.style.display = 'none';
element.classList.remove('fade-out');
}, 400);
}
// Adapt site if user is on mobile
function checkMobile() {
let userIsOnMobile = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) userIsOnMobile = true;})(navigator.userAgent||navigator.vendor||window.opera);
return userIsOnMobile;
}
const streamContainer = document.getElementById('streamContainer');
function loadStream() {
const iframedata = document.getElementById('streamUrl').value.replace('width="560" height="315" ', 'style=""');
if (iframedata.includes("youtube.com")){
streamContainer.innerHTML = ''; // Clear existing content
streamContainer.innerHTML = iframedata;
document.getElementsByTagName('iframe')[0].style.width = 'calc(' + streamContainer.width + '-20px)';
document.getElementsByTagName('iframe')[0].style.height = 'calc(' + streamContainer.height + '-20px)';
} else {
alert("Invalid embed URL.");
}
}
function setMapType(type) {
if (currentMapLayer) {
map.removeLayer(currentMapLayer);
}
if (type == 'light') {
currentMapLayer = lightModeLayer;
//document.querySelectorAll(".overlay-object").forEach(function(obj){
// obj.style.backgroundColor = "rgb(0, 0, 0, 0.5)"
//});
} else if (type == 'dark') {
currentMapLayer = darkModeLayer;
//document.querySelectorAll(".overlay-object").forEach(function(obj){
// obj.style.backgroundColor = "rgb(255, 255, 255, 0.2)"
//});
} else if (type == 'toggle'){
if (currentMapLayer == lightModeLayer){
currentMapLayer = darkModeLayer;
//document.querySelectorAll(".overlay-object").forEach(function(obj){
// obj.style.backgroundColor = "rgb(255, 255, 255, 0.2)"
//});
} else {
currentMapLayer = lightModeLayer;
//document.querySelectorAll(".overlay-object").forEach(function(obj){
// obj.style.backgroundColor = "rgb(0, 0, 0, 0.5)"
//});
}
}
map.addLayer(currentMapLayer);
if (currentMapLayer == lightModeLayer){
document.getElementsByClassName("leaflet-container")[0].style.backgroundColor = 'white';
document.getElementsByClassName("leaflet-container")[0].style.filter = 'contrast(100%) brightness(100%)';
} else {
document.getElementsByClassName("leaflet-container")[0].style.backgroundColor = 'black';
document.getElementsByClassName("leaflet-container")[0].style.filter = 'contrast(80%) brightness(130%)';
}
}
// Dark Mode Detection
function detectDarkMode() {
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
setMapType(isDarkMode ? 'dark' : 'light');
if (isDarkMode){
document.getElementById("dark").checked = true;
} else {
document.getElementById("light").checked = true;
}
//document.querySelector(`input[name="map-type"][value="${isDarkMode ? 'dark' : 'light'}"]`).checked = true;
}
detectDarkMode();
window.matchMedia('(prefers-color-scheme: dark)').addListener(detectDarkMode);
/**
* RainViewer radar animation part
* @type {number[]}
*/
var apiData = {};
var mapFrames = [];
var lastPastFramePosition = -1;
var radarLayers = [];
var doFuture = false; // Whether or not to show future radar
var optionKind = 'radar'; // can be 'radar' or 'satellite'
var optionTileSize = 256; // can be 256 or 512.
var optionColorScheme = 6; // from 0 to 8. Check the https://rainviewer.com/api/color-schemes.html for additional information
var optionSmoothData = 1; // 0 - not smooth, 1 - smooth
var optionSnowColors = 1; // 0 - do not show snow colors, 1 - show snow colors
var radarOpacity = 0.75
var alertOpacity = 0.4
var animationPosition = 0;
var animationTimer = false;
var loadingTilesCount = 0;
var loadedTilesCount = 0;
var alertData = []
var allalerts = [];
var displayFloodWarnings = true;
var displayFFloodWarnings = true;
var displayOtherWarnings = true;
var displaySpecWarnings = true;
var displayTorWarnings = true;
var displaySvrWarnings = true;
var displayTorReports = true;
var displayWndReports = true;
var displayHalReports = true;
var canRefresh = true;
var displayTorWatches = true;
var displaySvrWatches = true;
var watchesLoaded = false;
var alertsLoaded = false;
var showYoutubeEmbed = true;
var showspcOutlooks = true;
var showHurricaneTracks = true;
// Hurricane Icons
const td_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/td.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const ts_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/ts.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const cat1_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/cat1.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const cat2_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/cat2.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const cat3_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/cat3.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const cat4_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/cat4.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const cat5_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/cat5.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
const ptc_icon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/hurricanes/ptc.png',
iconSize: [36, 36],
iconAnchor: [18, 18],
});
function reportSettings(){
document.getElementById("alertsett").style.display = "none";
document.getElementById("radarsett").style.display = "none";
document.getElementById("reportsett").style.display = "block";
document.getElementById("mapsett").style.display = "none";
document.getElementById("alertset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("radarset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("reportset").style.backgroundColor = "#4c4cf0";
document.getElementById("mapset").style.backgroundColor = "rgb(51, 51, 51)";
}
function alertSettings(){
document.getElementById("alertsett").style.display = "block";
document.getElementById("radarsett").style.display = "none";
document.getElementById("reportsett").style.display = "none";
document.getElementById("mapsett").style.display = "none";
document.getElementById("alertset").style.backgroundColor = "#4c4cf0";
document.getElementById("radarset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("reportset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("mapset").style.backgroundColor = "rgb(51, 51, 51)";
}
function radarSettings(){
document.getElementById("alertsett").style.display = "none";
document.getElementById("radarsett").style.display = "block";
document.getElementById("reportsett").style.display = "none";
document.getElementById("mapsett").style.display = "none";
document.getElementById("alertset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("radarset").style.backgroundColor = "#4c4cf0";
document.getElementById("reportset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("mapset").style.backgroundColor = "rgb(51, 51, 51)";
}
function mapSettings(){
document.getElementById("alertsett").style.display = "none";
document.getElementById("radarsett").style.display = "none";
document.getElementById("reportsett").style.display = "none";
document.getElementById("mapsett").style.display = "block";
document.getElementById("alertset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("radarset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("reportset").style.backgroundColor = "rgb(51, 51, 51)";
document.getElementById("mapset").style.backgroundColor = "#4c4cf0";
}
let currentLocationMarker = null;
let watchId = null;
let isLocationOn = false;
let nowlat = null;
let nowlon = null;
function startUpdatingLocation() {
isLocationOn = document.getElementById("location").checked;
if (navigator.geolocation) {
if (watchId === null) {
watchId = navigator.geolocation.watchPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
nowlat = position.coords.latitude;
nowlon = position.coords.longitude;
// Place or update the custom circle marker at the user's location
if (currentLocationMarker) {
currentLocationMarker.setLatLng([nowlat, nowlon]);
} else {
const currentLocationIcon = L.icon({
iconUrl: 'https://busybird15.github.io/assets/locationicon.png',
iconSize: [26, 26],
iconAnchor: [13, 13], });
currentLocationMarker = L.marker([lat, lon], { icon: currentLocationIcon }).addTo(map);
if (isLocationOn) {
map.flyTo([lat, lon], 7);
}
document.getElementById("location").checked = true;
}
},
(error) => {
switch(error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Your position is unavailable. GPS is off or signal is too weak.");
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("Took too long to recieve a location, perhaps GPS is too weak.");
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred while getting your location.");
console.log("An unknown error occurred.");
break;
}
document.getElementById("location").checked = false;
clearCurrentLocationMarker();
isLocationOn = false;
},
{
enableHighAccuracy: true,
maximumAge: 0,
timeout: 10000
}
);
}
} else {
alert("Your browser doesn't support location. Try a different browser to use this feature.");
document.getElementById("location").checked = false;
}
}
function clearCurrentLocationMarker() {
if (currentLocationMarker) {
map.removeLayer(currentLocationMarker);
currentLocationMarker = null;
}
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
}
}
function showLocation() {
isLocationOn = document.getElementById("location").checked;
if (isLocationOn) {
startUpdatingLocation();
} else {
clearCurrentLocationMarker();
}
}
function floodChange(){
displayFloodWarnings = !displayFloodWarnings;
refresh();
saveSettings();
}
function ffloodChange(){
displayFFloodWarnings = !displayFFloodWarnings;
refresh();
saveSettings();
}
function othChange(){
displayOtherWarnings = !displayOtherWarnings;
refresh();
saveSettings();
}
function svrChange(){
displaySvrWarnings = !displaySvrWarnings;
refresh();
saveSettings();
}
function specChange(){
displaySpecWarnings = !displaySpecWarnings;
refresh();
saveSettings();
}
function torChange(){
displayTorWarnings = !displayTorWarnings;
refresh();
saveSettings();
}
function torRep(){
displayTorReports = !displayTorReports;
refresh();
saveSettings();
}
function wndRep(){
displayWndReports = !displayWndReports;
refresh();
saveSettings();
}
function halRep(){
displayHalReports = !displayHalReports;
refresh();
saveSettings();
}
function svrwwChange(){
displaySvrWatches = !displaySvrWatches;
refresh();
saveSettings();
}
function torwwChange(){
displayTorWatches = !displayTorWatches;
refresh();
saveSettings();
}
function showEmbed(tof){
showYoutubeEmbed = tof
saveSettings();
if (Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) > 1000 && showYoutubeEmbed){
document.getElementById('player').style.display = 'flex';
} else {
fadeOutElement('player');
}
}
function showOutlooks(tof){
showspcOutlooks = tof;
refresh();
saveSettings();
}
function toggleHurricanes(tof){
showHurricaneTracks = tof;
refresh();
saveSettings();
}
function settingsModal(){
document.getElementById("settingsModal").style.display = "block";
fadeOutElement("layerModal");
fadeOutElement("infoModal");
}
function toggleLayerModal(){
fadeOutElement("settingsModal");
document.getElementById("layerModal").style.display = "block";
fadeOutElement("infoModal");
}
function closeSettings(){
fadeOutElement("settingsModal");
fadeOutElement("layerModal");
fadeOutElement("infoModal");
}
function toggleInfoModal(){
fadeOutElement("settingsModal");
fadeOutElement("layerModal");
document.getElementById("infoModal").style.display = "flex";
}
function saveSettings() {
const settingsToSave = {
radarOpacity,
alertOpacity,
optionKind,
optionTileSize,
optionColorScheme,
optionSmoothData,
optionSnowColors,
doFuture,
displayFFloodWarnings,
displayFloodWarnings,
displayHalReports,
displayOtherWarnings,
displaySpecWarnings,
displaySvrWarnings,
displaySvrWatches,
displayTorReports,
displayTorWarnings,
displayTorWatches,
displayWndReports,
showYoutubeEmbed,
showspcOutlooks,
showHurricaneTracks
};
localStorage.setItem('preferences', JSON.stringify(settingsToSave));
}
console.log(localStorage.getItem('preferences'));
// Load the settings
const settings = JSON.parse(localStorage.getItem('preferences'));
if (settings){
radarOpacity = settings.radarOpacity;
alertOpacity = settings.alertOpacity;
optionKind = settings.optionKind;
optionTileSize = settings.optionTileSize;
optionColorScheme = settings.optionColorScheme;
optionSmoothData = settings.optionSmoothData;
optionSnowColors = settings.optionSnowColors;
doFuture = settings.doFuture;
displayFFloodWarnings = settings.displayFFloodWarnings;
displayFloodWarnings = settings.displayFloodWarnings;
displayHalReports = settings.displayHalReports;
displayOtherWarnings = settings.displayOtherWarnings;
displaySpecWarnings = settings.displaySpecWarnings;
displaySvrWarnings = settings.displaySvrWarnings;
displaySvrWatches = settings.displaySvrWatches;
displayTorReports = settings.displayTorReports;
displayTorWarnings = settings.displayTorWarnings;
displayTorWatches = settings.displayTorWatches;
displayWndReports = settings.displayWndReports;
showYoutubeEmbed = settings.showYoutubeEmbed;
showspcOutlooks = settings.showspcOutlooks;
showHurricaneTracks = settings.showHurricaneTracks;
if (optionKind == 'radar'){
document.getElementById("radar").checked = true;
} else {
document.getElementById("satellite").checked = true;
}
if (doFuture){
document.getElementById("future").checked = true;
} else {
document.getElementById("past").checked = true;
}
if (showYoutubeEmbed){
document.getElementById("embedid").checked = true;
} else {
document.getElementById("embedidN").checked = true;
}
if (showspcOutlooks){
document.getElementById("showoutlook").checked = true;
} else {
document.getElementById("hideoutlook").checked = true;
}
if (showHurricaneTracks){
document.getElementById("showhurricanes").checked = true;
} else {
document.getElementById("hidehurricanes").checked = true;
}
if (settings.optionSnowColors == 1){
document.getElementById("snow").checked = true;
} else {
document.getElementById("rain").checked = true;
}
if (settings.optionSmoothData == 1){
document.getElementById("rough").checked = true;
} else {
document.getElementById("smooth").checked = true;
}
document.getElementById('colors').value = optionColorScheme;
document.getElementById('alop').value = alertOpacity*100;
document.getElementById('radop').value = radarOpacity*100;
document.getElementById("tor").checked = displayTorWarnings;
document.getElementById("svr").checked = displaySvrWarnings;
document.getElementById("flood").checked = displayFloodWarnings;
document.getElementById("fflood").checked = displayFFloodWarnings;
document.getElementById("spec").checked = displaySpecWarnings;
document.getElementById("oth").checked = displayOtherWarnings;
document.getElementById("torww").checked = displayTorWatches;
document.getElementById("svrww").checked = displaySvrWatches;
document.getElementById("torr").checked = displayTorReports;
document.getElementById("wndr").checked = displayWndReports;
document.getElementById("halr").checked = displayHalReports;
} else if (settings == null && !checkMobile()) {
openModal(2);
}
function formatTimestamp(isoTimestamp) {
const date = new Date(isoTimestamp);
const options = {
year: 'numeric', month: 'long', day: 'numeric',
hour: '2-digit', minute: '2-digit', timeZoneName: 'short'
};
return date.toLocaleString('en-US', options);
}
function reverseSubarrays(arr) {
return arr.map(subArr => subArr.slice().reverse());
}
function findPair(list, target) {
for (let i = 0; i < list.length; i++) {
if (list[i][0] === target) {
return list[i][1];
}
}
return null
}
function findPairInDictionary(dicts, target) {
for (const dict of dicts) {
if (target in dict) {
return dict[target];
}
}
}
function convertDictsToArrayOfArrays(arr) {
return arr.map(obj => Object.values(obj));
}
async function getCSV(url) {
const response = await fetch(url);
const data = await response.text();
const lines = data.split('\n');
const headers = lines[0].split(',');
jsonData = lines.slice(1).map(line => {
const values = line.split(',');
return headers.reduce((obj, header, index) => {
obj[header] = values[index];
return obj;
}, {});
});
return JSON.stringify(jsonData, null, 2);
}
function radarOpacityChange() {
var sliderValue = document.getElementById('radop').value;
radarOpacity = sliderValue / 100;
refresh()
}
function alertOpacityChange() {
var sliderValue = document.getElementById('alop').value;
alertOpacity = sliderValue / 100;
refresh()
}
function onMapRightClick(e) {
var popLocation= e.latlng;
var popup = L.popup({"autoPan": true, 'maxheight': '600' , 'maxWidth': '500', 'className': 'alertpopup'})
.setLatLng(popLocation)
.setContent("Loading...")
.openOn(map);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://forecast.weather.gov/MapClick.php?lon=' + popLocation.lng + '&lat=' + popLocation.lat + '&FcstType=json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
try{
const data = JSON.parse(xhr.responseText)
const location = data.location;
var timestamp = new Date().getTime();
var content = '<div style="overflow-y: auto;"> <div style="display: flex; text-align: center; width: auto; padding: 5px; margin-bottom: 10px; border-radius: 5px; font-size: large; font-weight: bolder; color: white;">Current Conditions at ' + location.areaDescription + '</div>';
var index = 0;
data.data.hazard.forEach(function(hazard) {
var hazardColor = undefined;
var hazardFontColor = undefined;
if (hazard.includes("Tornado")) {
hazardColor = 'red';
hazardFontColor = 'white';
} else if (hazard.includes("Flood")) {
hazardColor = 'magenta'
hazardFontColor = 'black';
} else if (hazard.includes("Watch") || hazard.includes("Advisory")) {
hazardColor = 'yellow'
hazardFontColor = 'black';
} else if (hazard.includes("Warning")) {
hazardColor = 'orange'
hazardFontColor = 'black';
} else {
hazardColor = 'blue'
hazardFontColor = 'white';
}
content = content + '<a style="text-decoration: none;" target="_blank" href="' + data.data.hazardUrl[index] + '"><div style="background-color: ' + hazardColor + '; color: ' + hazardFontColor + '; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin-top: 5px; margin-bottom: 5px;"><b>' + hazard + '</b></p></div></a><br>';
index ++;
});
content = content + '<div style="display: flex; justify-content: center; text-align: center; width: auto; padding: 5px; margin-bottom: 10px; border-radius: 5px; font-size: large; font-weight: bolder; color: white; flex-direction: column; align-items: center;"><img style="border-radius: 10px; width: 70px; height: 70px;" src="https://forecast.weather.gov/newimages/large/' + data.currentobservation.Weatherimage + '">';
content = content + '<p><b>' + data.currentobservation.Weather + '</b></p></div>';
content = content + '<p style="margin:0px;"><b>Temperature: </b>' + data.currentobservation.Temp + '°F</p>';
content = content + '<p style="margin:0px;"><b>Humidity: </b>' + data.currentobservation.Relh + '%</p>';
content = content + '<p style="margin:0px;"><b>Dew Point: </b>' + data.currentobservation.Dewp + '°F</p>';
content = content + '<p style="margin:0px;"><b>Pressure (SLP): </b>' + data.currentobservation.SLP + 'inHg</p>';
content = content + '<p><b>Forecast: </b>' + data.data.text[0] + '</p>';
content = content + '<p><b>Forecast Office: </b><a style="color: lightblue;" target="_blank" href="' + data.credit + '">' + location.wfo + '</a></p>';
content = content + '<img class="alertgraphic" src="https://radar.weather.gov/ridge/standard/' + location.radar + '_loop.gif?t=' + timestamp + '">';
content = content + '<p><a style="color: lightblue;" target="_blank" href="https://busybird15.github.io/weather?lat=' + popLocation.lat + '&lon=' + popLocation.lng + '">See more</a></p>';
popup.setContent(content);
} catch { popup.setContent("Conditions unavailable for this location."); }
} else if (xhr.status === 400) {
popup.setContent("Conditions unavailable for this location.");
}
};
xhr.send();
};
map.on('contextmenu', onMapRightClick);
function getReport(polycoords, type){
var alertInfo = polycoords
var alertTitlecolor = 'white';
var alertTitlebackgroundColor = "white";
if (type == "Tornado Report"){
alertTitlecolor = 'black';
alertTitlebackgroundColor = "red";
} else if (type == "Wind Report"){
alertTitlebackgroundColor = "blue";
} else if (type == "Hail Report"){
alertTitlebackgroundColor = "green";
}
var construct = '<div style="overflow-y: auto;"> <div style="display: flex; justify-content: center; width: auto; padding: 5px; border-radius: 5px; font-size: 20px; font-weight: bolder; background-color: ' + alertTitlebackgroundColor + '; color: ' + alertTitlecolor + ';">' + type + '</div><br>';
const timestamp = alertInfo.Time;
const hour = parseInt(timestamp.substring(0, 2));
const minute = parseInt(timestamp.substring(2, 4));
const date = new Date();
date.setUTCHours(hour, minute); // Use setUTCHours to set the time in UTC
const options = {
timeZone: 'America/New_York',
hour: 'numeric',
minute: 'numeric',
hour12: true
};
const newTime = date.toLocaleString('en-US', options);
construct = construct + '<p style="margin: 0px;"><b>Report Time:</b> ' + newTime + '</p>';
if (type == "Tornado Report"){
construct = construct + '<p style="margin: 0px;"><b>EF-Rating:</b> ' + alertInfo.F_Scale + '</p>';
} else if (type == "Wind Report" && alertInfo.Speed != "UNK"){
construct = construct + '<p style="margin: 0px;"><b>Wind Speed:</b> ' + alertInfo.Speed + 'mph</p>';
} else if (type == "Hail Report"){
construct = construct + '<p style="margin: 0px;"><b>Hail Size:</b> ' + Math.ceil(alertInfo.Size / 100) + '"</p>';
}
construct = construct + '<p style="margin: 0px;"><b>Location:</b> ' + alertInfo.Location + "; " + alertInfo.County + ", " + alertInfo.State + " (" + alertInfo.Lat + ", " + alertInfo.Lon + ")" + '</p>';
construct = construct + '<p style="margin: 0px;"><b>Comments:</b> ' + alertInfo.Comments + '</p><br>'
construct = construct + '</div>'
return construct;
}
function loadReports() {
if (displayTorReports){
getCSV('https://www.spc.noaa.gov/climo/reports/today_filtered_torn.csv').then(json => {
var torreps = JSON.parse(json);
for (let i = 0; i < torreps.length; i++) {
try {
report = torreps[i];
const marker = L.marker([parseFloat(report.Lat), parseFloat(report.Lon)]).addTo(map);
marker.setIcon(L.divIcon({ className: 'tor-marker' }));
marker.bindPopup(getReport(report, "Tornado Report"), {"autoPan": true, 'maxheight': '300' , 'maxWidth': '250', 'className': 'alertpopup'});
}
catch{}
}
});;
}
if (displayHalReports) {
getCSV('https://www.spc.noaa.gov/climo/reports/today_filtered_hail.csv').then(json => {
var reps = JSON.parse(json);
for (let i = 0; i < reps.length; i++) {
try {
report = reps[i];
const marker = L.marker([parseFloat(report.Lat), parseFloat(report.Lon)]).addTo(map);
marker.setIcon(L.divIcon({ className: 'hail-marker' }));
marker.bindPopup(getReport(report, "Hail Report"), {"autoPan": true, 'maxheight': '300' , 'maxWidth': '250', 'className': 'alertpopup'});
}
catch{}
}
});;
}
if (displayWndReports) {
getCSV('https://www.spc.noaa.gov/climo/reports/today_filtered_wind.csv').then(json => {
var reps = JSON.parse(json);
for (let i = 0; i < reps.length; i++) {
try {
report = reps[i];
const marker = L.marker([parseFloat(report.Lat), parseFloat(report.Lon)]).addTo(map);
marker.setIcon(L.divIcon({ className: 'wind-marker' }));
marker.bindPopup(getReport(report, "Wind Report"), {"autoPan": true, 'maxheight': '300' , 'maxWidth': '250', 'className': 'alertpopup'});
}
catch{}
}
});;
}
return new Promise((resolve) => setTimeout(resolve, 1000));
}
function getHurricaneIcon(stormType, ssnum) {
switch (stormType) {
case 'TD':
return td_icon;
case 'TS':
return ts_icon;
case 'HU':
if (ssnum == 1){
return cat1_icon;
} else if (ssnum == 2){
return cat2_icon;
}
case 'MH':
if (ssnum == 3){
return cat3_icon;
} else if (ssnum == 4){
return cat4_icon;
} else if (ssnum == 5){
return cat5_icon;
}
default:
return ptc_icon;
}
}
function getTrackStyle(stormType) {
switch (stormType) {
case 'TD':
return "blue";
case 'TS':
return "green";
case 'Category 1 Hurricane':
return "yellow";
case 'Category 2 Hurricane':
return "orange";
case 'Category 3 Hurricane':
return "red";
case 'Category 4 Hurricane':
return "pink";
case 'Category 5 Hurricane':
return "purple";
default:
return "#00ff00";
}
}
// Function to parse the date string and convert it to the desired format
function formatHurricaneDateString(dateString) {
const [datePart, timePart, period, , timezone] = dateString.split(' ');
const date = new Date(`${datePart}T${timePart} ${period} ${timezone}`);
const dateOptions = { month: 'long', day: 'numeric' };
const timeOptions = { hour: '2-digit', minute: '2-digit', hour12: true, timeZoneName: 'short' };
const formattedDate = new Intl.DateTimeFormat('en-US', dateOptions).format(date);
const formattedTime = new Intl.DateTimeFormat('en-US', timeOptions).format(date);
return `${formattedDate} at ${formattedTime}`;
}
function fixDirection (dir) {
dir = parseInt(dir.replace("°", ""));
const directions = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
const index = Math.round(dir / 22.5) % 16;
return directions[index];
}
async function loadHurricanes() {
// Add the hurricane track
L.esri.featureLayer({
url: 'https://services9.arcgis.com/RHVPKKiFTONKtxq3/arcgis/rest/services/Active_Hurricanes_v1/FeatureServer/0',
pointToLayer: function (feature, latlng) {
var stormType = feature.properties.STORMTYPE;
var ssnum = feature.properties.SSNUM;
return L.marker(latlng, { icon: getHurricaneIcon(stormType, ssnum) });
},
style: function (feature) {
var stormType = feature.properties.STORMTYPE;
return {
color: getTrackStyle(stormType),
weight: 2,
opacity: 1
};
},
onEachFeature: function (feature, layer) {
var stormName = feature.properties.STORMNAME;
var stormType = feature.properties.STORMSRC;
var stormTypeID = feature.properties.STORMTYPE;
var maxWind = feature.properties.MAXWIND;
var gust = feature.properties.GUST;
var pressure = feature.properties.MSLP;
var direction = feature.properties.TCDIR;
var speed = feature.properties.TCSPD;
var dateTime = feature.properties.FLDATELBL; //formatHurricaneDateString(feature.properties.FLDATELBL);
var shortDateTime = feature.properties.DATELBL + " " + feature.properties.TIMEZONE;
var cat = feature.properties.SSNUM;
console.log(feature);
if (stormTypeID == "TS") {
stormType = "Tropical Storm";
} else if (stormTypeID == "TD") {
stormType = "Tropical Depression";
} else if (stormTypeID == "STD") {
stormType = "Sub-Tropical Depression";
} else if (stormTypeID == "MH") {
stormType = "Major Hurricane";
} else {
stormType = "Hurricane"
}
if (feature.properties.BASIN == "WP") {
var basin = "Western Pacific";
} else if (feature.properties.BASIN == "EP") {
var basin = "Eastern Pacific";
} else if (feature.properties.BASIN == "AL") {
var basin = "Atlantic";
} else {
var basin = "Unknown: " + feature.properties.BASIN;
}
var pressureText = (pressure && pressure !== 9999) ? pressure + " mb" : "Pressure data not available";
var directionText = (direction && direction !== 9999) ? direction + "°" : "Direction data not available";
var speedText = (speed && speed !== 9999) ? speed + " mph" : "Speed data not available";
var popupContent = '<div style="overflow-y: auto; display: flex; flex-direction: column;"> <div style="display: flex; flex-direction: row;"><img class="rotating" src="https://busybird15.github.io/assets/hurricanes/td.png"><div style="display: flex; justify-content: center; width: 100%; padding: 5px; padding-left: 10px; border-radius: 5px; font-size: 20px; font-weight: bolder; color: white;">' + stormType + ' ' + stormName + '</div></div><p style="margin: 0px;">';
popupContent += (cat && cat !== 0) ? '<br><b>Category:</b> CAT ' + cat.toString() + "<br>" : "<br>";
popupContent += "<b>Time:</b> " + shortDateTime + "<br>";
popupContent += "<b>Winds:</b> " + maxWind + " mph<br>";
popupContent += (gust && gust !== 0) ? "<b>Gusts:</b> " + gust + " mph<br><br>" : "<br>";
if (pressureText !== "Pressure data not available") {
popupContent += "<b>Pressure:</b> " + pressureText + "<br>";
}
if (directionText !== "Direction data not available" && speedText !== "Speed data not available") {
popupContent += "<b>Bearing:</b> " + fixDirection(directionText) + " at " + speedText + "<br><br>";
}
popupContent += "<b>Basin:</b> " + basin + "<br>";
popupContent += "<b>Identifier:</b> " + feature.properties.STORMTYPE + " " + feature.properties.STORMNUM + "<br>";
popupContent += "<b>Location:</b> " + feature.properties.LAT + ", " + feature.properties.LON + "<br>";
popupContent += "</p>"
var timestamp = new Date().getTime();
const currentYear = new Date().getFullYear();
if (basin == "Atlantic") { popupContent += '<br><img class="alertgraphic" src="https://www.nhc.noaa.gov/storm_graphics/AT' + String(feature.properties.STORMNUM).padStart(2, '0') + '/AL' + String(feature.properties.STORMNUM).padStart(2, '0') + currentYear + '_5day_cone_no_line_and_wind.png?t=' + timestamp + '">' }
if (basin == "Eastern Pacific") { popupContent += '<br><img class="alertgraphic" src="https://www.nhc.noaa.gov/storm_graphics/EP' + String(feature.properties.STORMNUM).padStart(2, '0') + '/EP' + String(feature.properties.STORMNUM).padStart(2, '0') + currentYear + '_5day_cone_no_line_and_wind.png?t=' + timestamp + '">' }
if (basin != "Western Pacific") { popupContent += '<p style="margin-bottom: 0px;">Graphics from the <a style="color: lightblue;" target="_blank" href="https://nhc.noaa.gov">NHC</a></p>'; }
popupContent += '<p style="width: 100%; overflow-x: clip;">==========================================================================================</p>'
layer.bindPopup(popupContent, {"autoPan": true, 'maxheight': '400' , 'maxWidth': '300', 'className': 'alertpopup'});
}
}).addTo(map);
// Add the hurricane cone layer with the new styling
L.esri.featureLayer({
url: 'https://services9.arcgis.com/RHVPKKiFTONKtxq3/ArcGIS/rest/services/Active_Hurricanes_v1/FeatureServer/4',
style: function (feature) {
return {
color: "#000000", // Black border
weight: 2, // Border weight
opacity: 1, // Full opacity for border
fillColor: "gray", // Cyan color for fill
fillOpacity: 0.2 // Low opacity for fill
};
},
onEachFeature: function (feature, layer) {}
}).addTo(map);
// Add the wind swath layer with different styling
L.esri.featureLayer({
url: 'https://services9.arcgis.com/RHVPKKiFTONKtxq3/ArcGIS/rest/services/Active_Hurricanes_v1/FeatureServer/2',
style: function (feature) {
return {
color: "gray", // Black border
weight: 2, // Border weight
opacity: 1, // Full opacity for border
fillColor: "gray", // Orange color for fill
fillOpacity: 0.4 // Higher opacity for fill
};
},
onEachFeature: function (feature, layer) {}
}).addTo(map);
// Add the watches and warnings layer using the TCWW field for styling
/*L.esri.featureLayer({
url: 'https://services9.arcgis.com/RHVPKKiFTONKtxq3/ArcGIS/rest/services/Active_Hurricanes_v1/FeatureServer/5',
style: function (feature) {
var tcww = feature.properties.TCWW; // Field used to determine style
switch (tcww) {
case 'HWR': // Hurricane Warning
return { color: 'rgb(255,0,0)', weight: 8, opacity: 1 };
case 'TWR': // Tropical Storm Warning
return { color: 'rgb(0,0,255)', weight: 3.4, opacity: 1 };
case 'HWA': // Hurricane Watch
return { color: 'rgb(255,174,185)', weight: 8, opacity: 1 };
case 'TWA': // Tropical Storm Watch
return { color: 'rgb(238,238,0)', weight: 8, opacity: 1 };
default:
return { color: 'gray', weight: 2, opacity: 1 };
}
},
onEachFeature: function (feature, layer) {
// Convert TCWW codes to full names
var tcww = feature.properties.TCWW;