-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscript.js
4664 lines (3970 loc) · 186 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
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
const key = 'Please use your own API key at maptiler.com';
const map = L.map('mapid', {
zoomControl: false,
minZoom: 2.5,
zoomSnap: 0,
terrainControl: false,
geolocateControl: false,
easeLinearity: 0.4,
bounceAtZoomLimits: false,
maxBounds: [[-84, -180], [84, 180]], // Restrict map boundaries
maxBoundsViscosity: 0.9 // Ensure the map view stops at the boundaries
}).setView([38.0, -100.4], 4);
/*
// Save position feature
map.on('moveend', () => {
const bounds = map.getBounds();
const zoomLevel = map.getZoom();
setTimeout(() => map.resize(), 0);
// Fetch data based on the current bounds and zoom level if needed
});
*/
// Create custom pane for label overlay
map.createPane('labelPane');
map.getPane('labelPane').style.zIndex = 200; // Higher z-index for labels
// Light Mode Layer
const lightModeLayer = L.maptilerLayer({
apiKey: key,
style: 'https://api.maptiler.com/maps/d3bdcfa3-d8d8-4bc1-958d-6d1780cb4de1/style.json?key=drXsj04WIDowwjjOrinL'
});
// Dark Mode Layer (base layer)
const darkModeLayer = L.maptilerLayer({
apiKey: key,
style: 'https://api.maptiler.com/maps/3d1b9c2b-3b90-4457-8310-fbd15c34d453/style.json?key=HKGa1lnD7ToUuzx5Ohp0'
});
// Label Layer (overlay on top of all modes)
const darkModeLabelLayer = L.maptilerLayer({
apiKey: key,
style: 'https://api.maptiler.com/maps/645f642d-36b4-42d1-8b02-b9968eff3443/style.json?key=HKGa1lnD7ToUuzx5Ohp0',
pane: 'labelPane', // Higher z-index pane for overlay
navigationControl: false,
geolocateControl: false
});
// Satellite Layer
const satelliteLayer = L.maptilerLayer({
apiKey: key,
style: 'https://api.maptiler.com/maps/dd940e48-cc35-41f3-b8e6-3942e4a1f75b/style.json?key=HKGa1lnD7ToUuzx5Ohp0'
});
let currentMapLayer;
// Function to set the map type and manage layers
function setMapType(type) {
// Remove the current base layer
if (currentMapLayer) {
map.removeLayer(currentMapLayer);
}
// Remove dark mode layer if switching away from dark mode
if (type !== 'dark' && map.hasLayer(darkModeLayer)) {
map.removeLayer(darkModeLayer);
}
// Set the base layer based on the selected type
if (type === 'light') {
currentMapLayer = lightModeLayer;
map.addLayer(darkModeLabelLayer); // Add label layer to light mode
} else if (type === 'dark') {
currentMapLayer = darkModeLayer;
map.addLayer(darkModeLayer); // Add dark mode base layer
map.addLayer(darkModeLabelLayer); // Add label layer to dark mode
} else if (type === 'satellite') {
currentMapLayer = satelliteLayer;
map.addLayer(darkModeLabelLayer); // Add label layer to satellite mode
}
// Add the selected base layer to the map
if (currentMapLayer) {
map.addLayer(currentMapLayer);
}
// Shift the map slightly to the right
const center = map.getCenter();
map.setView([center.lat, center.lng + 0.000000001], map.getZoom(), { animate: false });
// Save selected map type to localStorage
localStorage.setItem('selectedMapLayer', type);
}
// Function to load the saved map type or default to dark mode
function loadSavedMapType() {
const savedType = localStorage.getItem('selectedMapLayer') || 'dark'; // Default to dark
setMapType(savedType);
// Ensure the corresponding radio button is checked
document.querySelector(`input[name="map-type"][value="${savedType}"]`).checked = true;
}
// Call the function to load the map type on page load
loadSavedMapType();
map.attributionControl.setPrefix(false); // Removes the "Leaflet" text
// Remove the attribution control if it exists
if (map.attributionControl) {
map.attributionControl.remove();
}
var apiData = {};
var mapFrames = [];
var lastPastFramePosition = -1;
var radarLayers = [];
var polygons = [];
const reportMarkers = {};
var doFuture = true;
var optionKind = 'radar';
var optionTileSize = 256;
var optionColorScheme = 6; // Default color scheme for radar
var optionSmoothData = 1;
var optionSnowColors = 1;
var radarOpacity = 0.7;
var alertOpacity = 0.4;
var watchOpacity = 0.6;
var animationPosition = 0;
var animationTimer = false;
var loadingTilesCount = 0;
var loadedTilesCount = 0;
var radarON = true;
var satelliteON = false;
var alertON = true;
var watchesON = true;
var allalerts = [];
var displayTorReports = true;
var displayWndReports = true;
var displayHalReports = true;
var alertData = [];
var allalerts = [];
var displayFloodWarnings = true;
var displayFFloodWarnings = true;
var displayOtherWarnings = true;
var displaySpecWarnings = true;
var displayTorWarnings = true;
var displaySvrWarnings = true;
var displayTorWatches = true;
var displaySvrWatches = true;
var watchPolygons = {};
var watchesLoaded = false;
var alertsLoaded = false;
// Save settings to localStorage
function saveSettings() {
const settings = {
radarOpacity,
alertOpacity,
watchOpacity,
optionKind,
optionTileSize,
optionColorScheme,
optionSmoothData,
optionSnowColors,
radarON,
satelliteON,
alertON,
watchesON,
reportsON, // Save the report markers toggle state
hurricanesON, // Save the hurricane layers toggle state
selectedOutlooks: [], // Store selected checkmarks
mapType: currentMapLayer ? currentMapLayer.options.style : 'light', // Save the current map type
};
// Save selected checkmarks for outlooks
document.querySelectorAll('input[type=checkbox]').forEach((elem) => {
if (elem.checked) {
settings.selectedOutlooks.push(elem.value);
}
});
localStorage.setItem('weatherAppSettings', JSON.stringify(settings));
console.log('Settings saved:', settings);
}
// Load settings from localStorage
function loadSettings() {
const settings = JSON.parse(localStorage.getItem('weatherAppSettings'));
if (settings) {
radarOpacity = settings.radarOpacity;
alertOpacity = settings.alertOpacity;
watchOpacity = settings.watchOpacity;
optionKind = settings.optionKind || 'radar'; // Default to 'radar' if not set
optionTileSize = settings.optionTileSize;
optionColorScheme = settings.optionColorScheme;
optionSmoothData = settings.optionSmoothData;
optionSnowColors = settings.optionSnowColors;
radarON = settings.radarON;
satelliteON = settings.satelliteON;
alertON = settings.alertON;
watchesON = settings.watchesON;
reportsON = settings.reportsON;
hurricanesON = settings.hurricanesON !== undefined ? settings.hurricanesON : true; // Default to true if not set
// Load and apply selected checkmarks for outlooks
if (settings.selectedOutlooks && settings.selectedOutlooks.length > 0) {
settings.selectedOutlooks.forEach(outlookType => {
const checkbox = document.querySelector(`input[value="${outlookType}"]`);
if (checkbox) {
checkbox.checked = true;
const day = outlookType.split('_')[1];
updateOutlookType(day, outlookType); // Load the corresponding outlook layer
}
});
}
// Restore the map view (center and zoom)
if (settings.mapCenter && settings.mapZoom) {
const center = [settings.mapCenter.lat, settings.mapCenter.lng];
map.setView(center, settings.mapZoom);
}
// Restore report markers toggle
if (settings.reportsON) {
reportsON = settings.reportsON;
if (reportsON) {
startAutoRefresh(); // Start auto-refreshing if reports are on
} else {
stopAutoRefresh();
}
}
// Update UI labels, sliders, and buttons
document.getElementById('smoothing-button').innerHTML = optionSmoothData == 0 ? '<i class="fa-solid fa-wave-square"></i> Smoothing Off' : '<i class="fa-solid fa-wave-square"></i> Smoothing On';
document.getElementById('highres-button').innerHTML = optionTileSize == 256 ? '<i class="fa-solid fa-highlighter"></i> Low Res Radar' : '<i class="fa-solid fa-highlighter"></i> High Res Radar';
document.getElementById('colors').value = optionColorScheme;
// Update sliders and their values
document.getElementById('alert-opacity-slider').value = alertOpacity;
document.getElementById('alert-opacity-value').textContent = alertOpacity;
document.getElementById('radar-opacity-slider').value = radarOpacity;
document.getElementById('radar-opacity-value').textContent = radarOpacity;
// Update radar type radio button
document.querySelector(`input[name="radar-type"][value="${optionKind}"]`).checked = true;
// Update button styles based on state
const alertButton = document.getElementById("refreshalerts");
alertButton.style.backgroundColor = alertON ? "white" : "#636381";
alertButton.style.color = alertON ? "#7F1DF0" : "white";
alertButton.style.border = alertON ? "#636381 2px solid" : "2px solid white";
const alertsMenuButton = document.getElementById("alerts-menu-button");
alertsMenuButton.style.backgroundColor = alertON ? "white" : "#636381";
alertsMenuButton.style.color = alertON ? "#7F1DF0" : "white";
alertsMenuButton.style.border = alertON ? "#636381 2px solid" : "2px solid white";
const watchButton = document.getElementById("togglewatches");
watchButton.style.backgroundColor = watchesON ? "white" : "#636381";
watchButton.style.color = watchesON ? "#7F1DF0" : "white";
watchButton.style.border = watchesON ? "#636381 2px solid" : "2px solid white";
// Update hurricane button state
const hurricaneButton = document.getElementById("toggle-hurricanes");
hurricaneButton.style.backgroundColor = hurricanesON ? "white" : "#636381";
hurricaneButton.style.color = hurricanesON ? "#7F1DF0" : "white";
// Toggle hurricane layer based on saved settings
toggleHurricanes(hurricanesON);
} else {
// If no settings found, ensure default state
hurricanesON = true; // Default hurricane layer to ON
toggleHurricanes(hurricanesON); // Show the hurricane layer by default
}
// Ensure initialization with the loaded radar type
initialize(apiData, optionKind);
}
// Event listener for checkboxes to toggle outlook layers and save settings
document.querySelectorAll('input[type=checkbox]').forEach((elem) => {
elem.addEventListener('change', function () {
const outlookType = this.value;
if (this.checked) {
// Uncheck all other checkboxes before checking the current one
document.querySelectorAll('input[type=checkbox]').forEach(cb => {
if (cb !== this) {
cb.checked = false;
}
});
const day = outlookType.split('_')[1];
updateOutlookType(day, outlookType);
} else if (!this.checked && currentLayer) {
removeCurrentLayer(() => {
lastSelectedOutlook = '';
});
}
// Save settings after any change
saveSettings();
});
});
// Call loadSettings when the page is ready to load saved settings
document.addEventListener('DOMContentLoaded', function () {
loadSettings();
});
map.createPane('polygonPane');
map.getPane('polygonPane').style.zIndex = 400; // higher z-index for polygon
map.createPane('borderPane');
map.getPane('borderPane').style.zIndex = 300; // lower z-index for border
let isThrottled = false;
map.on('move', () => {
if (!isThrottled) {
isThrottled = true;
setTimeout(() => {
// Update radar loop or data
isThrottled = false;
}, 400); // Adjust delay as needed
}
});
function debounce(fn, delay, immediate = false) {
let timer = null;
return function (...args) {
const context = this;
const later = () => {
timer = null;
if (!immediate) fn.apply(context, args);
};
const callNow = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(later, delay);
if (callNow) fn.apply(context, args);
};
}
document.addEventListener('DOMContentLoaded', function() {
loadSettings(); // Load settings when the page loads
});
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;
}
document.querySelectorAll("a").forEach(function(item) {
if (item.href == "https://www.maptiler.com/") {
item.style.bottom = "58px";
item.style.left = "6px";
}
});
function findPairInDictionary(dicts, target) {
for (const dict of dicts) {
console.log(dict + " with target " + target);
console.log(alertData);
if (target in dict) {
return dict[target];
}
}
console.log("Couldn't find obj.");
}
function convertDictsToArrayOfArrays(arr) {
return arr.map(obj => Object.values(obj));
}
function getAlert(alertInfo) {
var alertTitle = document.getElementById('alert_title');
var alertTitlecolor = 'white';
var alertTitlebackgroundColor = "white";
var alertBorderColor = "#1A1A1A";
var alertBorderWidth = "0px";
if (alertInfo.properties.event.includes("Severe Thunderstorm")) {
alertTitlebackgroundColor = "gold";
if (alertInfo.properties.description.toLowerCase().includes("80 mph") || alertInfo.properties.description.toLowerCase().includes("destructive")) {
alertBorderColor = "gold";
alertBorderWidth = "0px";
}
} else if (alertInfo.properties.event.includes("Tornado")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "red";
if (alertInfo.properties.description.toLowerCase().includes("tornado emergency")) {
alertBorderColor = "maroon";
alertBorderWidth = "0px";
}
} else if (alertInfo.properties.event.includes("Flash Flood Warning")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "lime";
if (alertInfo.properties.description.toLowerCase().includes("flash flood emergency")) {
alertBorderColor = "darkgreen";
alertBorderWidth = "0px";
}
} else if (alertInfo.properties.event.includes("Special Weather")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "#ecd4b1";
}
if (alertInfo.properties.event.includes("Special Marine")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "orange";
}
if (alertInfo.properties.event.includes("Extreme Wind")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "pink";
}
if (alertInfo.properties.event.includes("Snow Squall")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "#5DE2E7";
}
var construct = '<div class="alert-header" style="background-color: ' + alertTitlebackgroundColor + '; color: ' + alertTitlecolor + ';">' + alertInfo.properties.event + '</div><div style="overflow-y: auto; border: ' + alertBorderWidth + ' solid ' + alertBorderColor + ';">';
construct = construct + '<p style="margin: 0px;"><b>Issued:</b> ' + formatTimestamp(alertInfo.properties.sent) + '</p>';
construct = construct + '<p style="margin: 0px;"><b>Expires:</b> ' + formatTimestamp(alertInfo.properties.expires) + '</p>';
construct = construct + '<p style="margin: 0px;"><b>Areas:</b> ' + alertInfo.properties.areaDesc + '</p><br>';
try {
var hazards = alertInfo.properties.description.split("HAZARD...")[1].split("\n\n")[0].replace(/\n/g, " ");
} catch {
var hazards = "No hazards identified.";
}
construct = construct + '<p style="margin: 0px;"><b>Hazards: </b>' + hazards + '</p>';
try {
// Match everything after "IMPACTS..." until we hit two newlines, an asterisk, or the end of the string
var impacts = alertInfo.properties.description.match(/IMPACTS?\.\.\.(.*?)(?:\n\n|\*|$)/s)[1]
.replace(/\n/g, " ") // Replace newlines within the impacts with spaces for formatting
.trim(); // Clean up any leading or trailing whitespace
} catch {
try {
// Match everything after "IMPACT..." until we hit two newlines, an asterisk, or the end of the string
var impacts = alertInfo.properties.description.match(/IMPACT?\.\.\.(.*?)(?:\n\n|\*|$)/s)[1]
.replace(/\n/g, " ") // Replace newlines within the impacts with spaces for formatting
.trim(); // Clean up any leading or trailing whitespace
} catch {
// If no impacts found, set default message
var impacts = "No impacts identified.";
}
}
// Add the impacts to the constructed content
construct = construct + '<p style="margin: 0px;"><b>Impacts: </b>' + impacts + '</p><br>';
var description = alertInfo.properties.description.replace(/(?:SVR|FFW|TOR|SMW)\d{4}/g, "").replace(/\n/g, "<br>");
construct = construct + '<button class="more-info-button" onclick="showAlertPopup(' + JSON.stringify(alertInfo).replace(/"/g, '"') + ')"><i class="fa-solid fa-info-circle"></i> More Info</button>';
construct = construct + '</div>';
return construct;
}
function formatTimestamp(isoTimestamp) {
const date = new Date(isoTimestamp);
return new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric',
hour: '2-digit', minute: '2-digit', hour12: true,
timeZoneName: 'short'
}).format(date);
}
function formatWatchDate(timestamp) {
const year = parseInt(timestamp.slice(0, 4));
const month = parseInt(timestamp.slice(4, 6)) - 1; // JavaScript months are 0-based
const day = parseInt(timestamp.slice(6, 8));
const hour = parseInt(timestamp.slice(8, 10));
const minute = parseInt(timestamp.slice(10, 12));
return new Date(Date.UTC(year, month, day, hour, minute));
}
function formatDate(inputDateString) {
const inputDate = new Date(inputDateString);
return new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric',
hour: '2-digit', minute: '2-digit', hour12: true,
timeZoneName: 'short'
}).format(inputDate);
}
function getAlert(alertInfo) {
var alertTitlecolor = 'white';
var alertTitlebackgroundColor = "white";
var alertBorderColor = "#1A1A1A";
var alertBorderWidth = "0px";
if (alertInfo.properties.event.includes("Severe Thunderstorm")) {
alertTitlebackgroundColor = "gold";
if (alertInfo.properties.description.toLowerCase().includes("80 mph wind gusts") || alertInfo.properties.description.toLowerCase().includes("destructive storm")) {
alertBorderColor = "gold";
alertBorderWidth = "0px";
}
} else if (alertInfo.properties.event.includes("Tornado")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "red";
if (alertInfo.properties.description.toLowerCase().includes("tornado emergency")) {
alertBorderColor = "maroon";
alertBorderWidth = "0px";
}
} else if (alertInfo.properties.event.includes("Flash Flood Warning")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "lime";
if (alertInfo.properties.description.toLowerCase().includes("flash flood emergency")) {
alertBorderColor = "darkgreen";
alertBorderWidth = "0px";
}
} else if (alertInfo.properties.event.includes("Special Weather")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "#ecd4b1";
}
if (alertInfo.properties.event.includes("Special Marine")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "orange";
}
if (alertInfo.properties.event.includes("Extreme Wind")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "pink";
}
if (alertInfo.properties.event.includes("Snow Squall")) {
alertTitlecolor = 'white';
alertTitlebackgroundColor = "#5DE2E7";
}
var construct = '<div class="alert-header" style="background-color: ' + alertTitlebackgroundColor + '; color: ' + alertTitlecolor + ';">' + alertInfo.properties.event + '</div>';
var customMessages = '';
if (alertInfo.properties.description.includes("TORNADO EMERGENCY")) {
customMessages += '<div style="background-color: magenta; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>THIS IS AN EMERGENCY SITUATION</b></p></div>';
}
if (alertInfo.properties.description.includes("FLASH FLOOD EMERGENCY")) {
customMessages += '<div style="background-color: magenta; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>THIS IS AN EMERGENCY SITUATION</b></p></div>';
}
else if (alertInfo.properties.description.includes("PARTICULARLY DANGEROUS SITUATION")) {
customMessages += '<div style="background-color: magenta; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>THIS IS A PARTICULARLY DANGEROUS SITUATION</b></p></div>';
}
else if (alertInfo.properties.description.includes("confirmed tornado")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>THIS TORNADO IS ON THE GROUND</b></p></div>';
} else if (alertInfo.properties.description.includes("reported tornado")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>THIS TORNADO IS ON THE GROUND</b></p></div>';
}
if (alertInfo.properties.description.includes("DESTRUCTIVE")) {
customMessages += '<div style="background-color: red; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>DAMAGE THREAT: DESTRUCTIVE</b></p></div>';
} else if (alertInfo.properties.description.includes("considerable")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>DAMAGE THREAT: CONSIDERABLE</b></p></div>';
}
else if (alertInfo.properties.description.includes("Two inch hail")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>DAMAGE THREAT: CONSIDERABLE</b></p></div>';
}
else if (alertInfo.properties.description.includes("Tennis")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin-bottom: 3px; display: flex; justify-content: center; text-align: center;"><p style="margin: 3px 0; color: white;"><b>DAMAGE THREAT: CONSIDERABLE</b></p></div>';
}
// Extract source from the description
let source = "No source identified.";
try {
source = alertInfo.properties.description.match(/SOURCE\.\.\.(.*?)(?=\n[A-Z]|$)/s)[1].replace(/\n/g, " ");
} catch (e) {
console.log("Error extracting source:", e);
}
construct += customMessages;
construct += '<div style="overflow-y: auto; border: ' + alertBorderWidth + ' solid ' + alertBorderColor + ';">';
construct += '<p style="margin: 0;"><b>Issued:</b> ' + formatTimestamp(alertInfo.properties.sent) + '</p>';
construct += '<p style="margin: 0;"><b>Expires:</b> ' + formatTimestamp(alertInfo.properties.expires) + '</p>';
construct += '<p style="margin: 0;"><b>Source:</b> ' + source + '</p><br>';
// Extracting hazards
var hazards = "No hazards identified.";
try {
hazards = alertInfo.properties.description.match(/HAZARD\.\.\.(.*?)(?=\n[A-Z]|\*|$)/s)[1].replace(/\n/g, " ");
} catch (e) {
console.log("Error extracting hazards:", e);
}
construct += '<p style="margin: 0;"><b>Hazards: </b>' + hazards + '</p>';
// Extracting impacts
var impacts = "No impacts identified.";
try {
// Match everything after "IMPACTS..." until we hit two newlines, an asterisk, or the end of the string
var impacts = alertInfo.properties.description.match(/IMPACTS?\.\.\.(.*?)(?:\n\n|\*|$)/s)[1]
.replace(/\n/g, " ") // Replace newlines within the impacts with spaces for formatting
.trim(); // Clean up any leading or trailing whitespace
} catch {
try {
// Match everything after "IMPACT..." until we hit two newlines, an asterisk, or the end of the string
var impacts = alertInfo.properties.description.match(/IMPACT?\.\.\.(.*?)(?:\n\n|\*|$)/s)[1]
.replace(/\n/g, " ") // Replace newlines within the impacts with spaces for formatting
.trim(); // Clean up any leading or trailing whitespace
} catch {
// If no impacts found, set default message
var impacts = "No impacts identified.";
}
}
// Adding the impacts to the construct
construct += '<p style="margin: 0;"><b>Impacts: </b>' + impacts + '</p><br>';
// Extracting description
var description = alertInfo.properties.description.replace(/(?:SVR|FFW|TOR)\d{4}/g, "").replace(/\n/g, "<br>");
construct += '<button class="more-info-button" onclick="showAlertPopup(' + JSON.stringify(alertInfo).replace(/"/g, '"') + ')"><i class="fa-solid fa-info-circle"></i> More Info</button>';
construct += '</div>';
return construct;
}
function formatTimestamp(isoTimestamp) {
const date = new Date(isoTimestamp);
return new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric',
hour: '2-digit', minute: '2-digit', hour12: true,
timeZoneName: 'short'
}).format(date);
}
function changeRadarPosition(position, preloadOnly, force) {
while (position >= mapFrames.length) {
position -= mapFrames.length;
}
while (position < 0) {
position += mapFrames.length;
}
var currentFrame = mapFrames[animationPosition];
var nextFrame = mapFrames[position];
addLayer(nextFrame);
if (preloadOnly || (isTilesLoading() && !force)) {
return;
}
animationPosition = position;
if (radarLayers[currentFrame.path]) {
radarLayers[currentFrame.path].setOpacity(0);
}
radarLayers[nextFrame.path].setOpacity(radarOpacity);
var pastOrForecast = nextFrame.time > Date.now() / 1000 ? 'Future' : (nextFrame.time === mapFrames[lastPastFramePosition].time ? 'Current' : 'Past');
document.getElementById("timestamp").innerHTML = pastOrForecast + " • " + formatDate(new Date(nextFrame.time * 1000).toISOString());
}
function logAlert(alertInfo) {
var alertLog = document.getElementById('alert-log');
var noAlertsMessage = document.getElementById('no-alerts-message');
var alertClass = '';
// Determine the alert class based on the event type
if (alertInfo.properties.event.includes("Severe Thunderstorm")) {
alertClass = 'alert-severe-thunderstorm';
} else if (alertInfo.properties.event.includes("Tornado")) {
alertClass = 'alert-tornado';
} else if (alertInfo.properties.event.includes("Flash Flood Warning")) {
alertClass = 'alert-flash-flood';
} else if (alertInfo.properties.event.includes("Special Weather")) {
alertClass = 'alert-special-weather';
} else if (alertInfo.properties.event.includes("Special Marine")) {
alertClass = 'alert-special-marine';
} else if (alertInfo.properties.event.includes("Extreme Wind")) {
alertClass = 'alert-extreme-wind';
}
else if (alertInfo.properties.event.includes("Snow Squall")) {
alertClass = 'alert-snow-squall';
}
if (alertClass) {
var listItem = document.createElement('li');
// Check for duplicate alerts
var alertExists = false;
for (var i = 0; i < alertLog.children.length; i++) {
var child = alertLog.children[i];
if (child.getAttribute('data-alert-id') === alertInfo.properties.id) {
alertExists = true;
break;
}
}
if (alertExists) {
return; // Alert already exists, skip adding it
}
// Set data attributes for alert ID and issued time
listItem.setAttribute('data-alert-id', alertInfo.properties.id);
listItem.setAttribute('data-issued-time', alertInfo.properties.sent);
// Build the innerHTML of the list item
listItem.innerHTML =
`<div class="alert-header ${alertClass}" style="padding: 8px; font-size: 17px; font-weight: bolder;">
${alertInfo.properties.event}
</div>
<div style="margin-top: 2px; font-size: 16px;">
<b>Issued:</b> ${formatTimestamp(alertInfo.properties.sent)}<br>
<b>Expires:</b> ${formatTimestamp(alertInfo.properties.expires)}<br>
<b>Areas:</b> ${alertInfo.properties.areaDesc}
</div>
<div class="alert-buttons" style="margin-top: 2px;">
<button class="more-info-button" onclick="showAlertPopup(${JSON.stringify(alertInfo).replace(/"/g, '"')})">
<i class="fa-solid fa-info-circle"></i> More Info
</button>
<button class="more-info-button" onclick="zoomToAlert(${JSON.stringify(alertInfo.geometry.coordinates).replace(/"/g, '"')})">
<i class="fa-solid fa-eye"></i> Show Me
</button>
</div>`;
// Insert the alert in reverse chronological order based on issued time
let inserted = false;
const newAlertTime = new Date(alertInfo.properties.sent);
for (let i = 0; i < alertLog.children.length; i++) {
const existingAlertTime = new Date(alertLog.children[i].getAttribute('data-issued-time'));
// If the new alert is more recent, insert it before the older alert
if (newAlertTime > existingAlertTime) {
alertLog.insertBefore(listItem, alertLog.children[i]);
inserted = true;
break;
}
}
// If the alert is the oldest, append it at the end of the list
if (!inserted) {
alertLog.appendChild(listItem);
}
// Hide the "No active alerts" message since we have at least one alert
noAlertsMessage.style.display = 'none';
noAlertsMessage.classList.remove('centered-alert');
}
// Show "No active alerts" message if there are no alerts and alerts are turned on
if (alertLog.children.length === 0 && alertON) {
noAlertsMessage.style.display = 'block';
noAlertsMessage.querySelector('p').innerText = 'No active alerts';
noAlertsMessage.classList.add('centered-alert');
document.getElementById('toggle-alerts-button').style.display = 'none';
} else {
noAlertsMessage.classList.remove('centered-alert');
}
}
function updateAlertList(newAlerts) {
var alertLog = document.getElementById('alert-log');
alertLog.innerHTML = ''; // Clear existing alerts
// Sort new alerts by 'sent' date in descending order (newest first)
newAlerts.sort((a, b) => new Date(b.properties.sent) - new Date(a.properties.sent));
// Add sorted alerts to the log
newAlerts.forEach(alert => logAlert(alert));
}
function showAlertPopup(alertInfo) {
document.getElementById('popup-title').innerText = alertInfo.properties.event;
document.getElementById('popup-title').style.backgroundColor = getAlertHeaderColor(alertInfo.properties.event);
// Custom messages
let customMessages = '';
if (alertInfo.properties.description.includes("TORNADO EMERGENCY")) {
customMessages += '<div style="background-color: magenta; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>THIS IS AN EMERGENCY SITUATION</b></p></div><br>';
}
if (alertInfo.properties.description.includes("FLASH FLOOD EMERGENCY")) {
customMessages += '<div style="background-color: magenta; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>THIS IS AN EMERGENCY SITUATION</b></p></div><br>';
}
else if (alertInfo.properties.description.includes("PARTICULARLY DANGEROUS SITUATION")) {
customMessages += '<div style="background-color: magenta; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>THIS IS A PARTICULARLY DANGEROUS SITUATION</b></p></div><br>';
}
else if (alertInfo.properties.description.includes("confirmed tornado")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>THIS TORNADO IS ON THE GROUND</b></p></div><br>';
} else if (alertInfo.properties.description.includes("reported tornado")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>THIS TORNADO IS ON THE GROUND</b></p></div><br>';
}
if (alertInfo.properties.description.includes("DESTRUCTIVE")) {
customMessages += '<div style="background-color: red; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>DAMAGE THREAT: DESTRUCTIVE</b></p></div><br>';
}
else if (alertInfo.properties.description.includes("considerable")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>DAMAGE THREAT: CONSIDERABLE</b></p></div><br>';
}
else if (alertInfo.properties.description.includes("Two inch hail")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>DAMAGE THREAT: CONSIDERABLE</b></p></div><br>';
} else if (alertInfo.properties.description.includes("Tennis")) {
customMessages += '<div style="background-color: orange; border-radius: 5px; margin: 0px; display: flex; justify-content: center; text-align: center;"><p style="margin: 5px 0; color: white;"><b>DAMAGE THREAT: CONSIDERABLE</b></p></div><br>';
}
// Extract source from the description
let source = "No source identified.";
try {
source = alertInfo.properties.description.match(/SOURCE\.\.\.(.*?)(?=\n[A-Z]|$)/s)[1].replace(/\n/g, " ");
} catch (e) {
console.log("Error extracting source:", e);
}
document.getElementById('popup-details').innerHTML = `${customMessages}<b>Issued:</b> ${formatTimestamp(alertInfo.properties.sent)}<br><b>Expires:</b> ${formatTimestamp(alertInfo.properties.expires)}<br><b>Source:</b> ${source}`;
// Extract hazards and impacts
let hazards = "No hazards identified.";
try {
hazards = alertInfo.properties.description.match(/HAZARD\.\.\.(.*?)(?=\n[A-Z]|$)/s)[1].replace(/\n/g, " ");
} catch (e) {
console.log("Error extracting hazards:", e);
}
let impacts = "No impacts identified.";
try {
impacts = alertInfo.properties.description.match(/IMPACTS?\.\.\.(.*?)(?:\n\n|\*|$)/s)[1]
.replace(/\n/g, " ") // Replace newlines within the impacts with spaces for formatting
.trim(); // Clean up any leading or trailing whitespace
} catch (e) {
try {
impacts = alertInfo.properties.description.match(/IMPACT\.\.\.(.*?)(?:\n\n|\*|$)/s)[1]
.replace(/\n/g, " ") // Replace newlines within the impacts with spaces for formatting
.trim(); // Clean up any leading or trailing whitespace
} catch (e) {
console.log("Error extracting impacts:", e);
}
}
// Add hazards and impacts to the popup with reduced margin below impacts
document.getElementById('popup-hazards-impacts').innerHTML = `
<p style="margin: 0;"><b>Hazards:</b> ${hazards}</p>
<p style="margin: 0;"><b>Impacts:</b> ${impacts}</p>
`;
// Process the description to clean up odd line breaks
var cleanedDescription = alertInfo.properties.description
.replace(/(?:SVR|FFW|TOR)\d{4}/g, "") // Remove specific codes like SVR, FFW, and TOR
.replace(/\*/g, "") // Remove asterisks
.replace(/\n{2,}/g, "<br><br>") // Replace two or more newlines with two <br> tags for paragraph breaks
.replace(/\n/g, " "); // Replace single newlines with a space to avoid odd breaks in sentences
document.getElementById('popup-description').innerHTML = `<b>Description:</b><br>
<p style="margin: 8px 0 0 4px; padding-left: 10px; border-left: 5px solid ${getAlertHeaderColor(alertInfo.properties.event)}; border-radius: 5px;">
${cleanedDescription}
</p>`;
document.getElementById('popup-action').innerHTML = `<b>Action Recommended:</b> ${alertInfo.properties.instruction || 'No specific actions recommended.'}<br><br><b>Areas:</b> ${alertInfo.properties.areaDesc || 'No area specified.'}`;
var popup = document.getElementById('alert-popup');
popup.classList.add('show');
}
function getAlertHeaderColor(event) {
if (event.includes("Severe Thunderstorm")) return "gold";
if (event.includes("Tornado")) return "red";
if (event.includes("Flash Flood Warning")) return "lime";
if (event.includes("Special Weather")) return "#ecd4b1";
if (event.includes("Special Marine")) return "orange";
if (event.includes("Extreme Wind")) return "pink";
if (event.includes("Snow Squall")) return "#5DE2E7";
return "white";
}
function closeAlertPopup() {
// Get the popup element
var popup = document.getElementById('alert-popup');
// Add fade-out class to initiate the animation
popup.classList.add('fade-out');
// Set a timeout to remove 'show' and 'fade-out' after the animation ends (300ms)
setTimeout(() => {
popup.classList.remove('show', 'fade-out');
}, 300);
// Stop the speech synthesis when the popup is closed
window.speechSynthesis.cancel();
isPlaying = false;
// Reset the Play/Pause button to its "Play Alert" state
const playPauseBtn = document.getElementById('play-pause-btn');
playPauseBtn.innerHTML = '<i class="fa-solid fa-volume-up" style="margin-right: 5px;"></i> Play Alert';
updateButtonStyle(playPauseBtn, false); // Set to "off" style when popup is closed
}
function zoomToAlert(coordinates) {
// Reverse the subarrays if necessary (assuming coordinates[0] is an array of [lng, lat] pairs)
var latLngs = reverseSubarrays(coordinates[0]);
// Create a LatLngBounds object from the coordinates
var bounds = L.latLngBounds(latLngs);
// Calculate the center of the bounds
var center = bounds.getCenter();
// Get the zoom level that would fit the bounds
var targetZoom = map.getBoundsZoom(bounds);
// Decrease the zoom level by 1 or adjust as needed to zoom out
var zoomOutLevel = targetZoom - 1; // Adjust this value to zoom out more or less
// Ensure zoomOutLevel is within the map's min and max zoom levels
zoomOutLevel = Math.max(map.getMinZoom(), Math.min(map.getMaxZoom(), zoomOutLevel));
// Use flyTo for a smooth animated transition
map.flyTo(center, zoomOutLevel);
}
function loadAlerts() {
if (!alertON) return; // Don't load alerts if alertON is false
console.log("Loading alerts");
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.weather.gov/alerts/active', true);
xhr.setRequestHeader('Accept', 'Application/geo+json');
xhr.onreadystatechange = function() {
console.log("running");
if (xhr.readyState === 4 && xhr.status === 200) {
var alerts = JSON.parse(xhr.responseText).features;
// Assign priority based on event type
alerts.forEach(function(alert) {
if (alert.properties.event.includes("Special Marine")) {
alert.priority = 7;
} else if (alert.properties.event.includes("Special Weather")) {
alert.priority = 6;
} else if (alert.properties.event.includes("Snow Squall")) {
alert.priority = 5;
} else if (alert.properties.event.includes("Flash Flood Warning")) {
alert.priority = 4;
} else if (alert.properties.event.includes("Severe Thunderstorm")) {
alert.priority = 3;
} else if (alert.properties.event.includes("Extreme Wind")) {
alert.priority = 2;
} else if (alert.properties.event.includes("Tornado")) {
alert.priority = 1;
} else {
alert.priority = 8; // Lowest priority for other events
}
});
// Sort by priority and then by sent time (oldest to newest)
alerts.sort((a, b) => {
if (a.priority !== b.priority) {
return a.priority - b.priority; // Sort by priority
}
return new Date(a.properties.sent) - new Date(b.properties.sent); // If same priority, sort by time
});
// Clear existing polygons and borders
polygons.forEach(function(polygon) {
map.removeLayer(polygon);
});
polygons = []; // Reset the polygons array
document.getElementById('alert-log').innerHTML = ''; // Clear existing alert log
// Reverse to display newest first within each priority
alerts.reverse().forEach(function(alert) {