forked from mutability/dump1090
-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathscript.js
2854 lines (2438 loc) · 103 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
// -*- mode: javascript; indent-tabs-mode: nil; c-basic-offset: 8 -*-
"use strict";
// Define our global variables
var OLMap = null;
var StaticFeatures = new ol.Collection();
var SiteCircleFeatures = new ol.Collection();
var PlaneIconFeatures = new ol.Collection();
var PlaneTrailFeatures = new ol.Collection();
var Planes = {};
var PlanesOrdered = [];
var PlaneFilter = {};
var SelectedPlane = null;
var SelectedAllPlanes = false;
var HighlightedPlane = null;
var FollowSelected = false;
var infoBoxOriginalPosition = {};
var customAltitudeColors = true;
var myAdsbStatsSiteUrl = null;
var ADSB_Enabled = true;
var UAT_Enabled = false;
var SpecialSquawks = {
'7500' : { cssClass: 'squawk7500', markerColor: 'rgb(255, 85, 85)', text: 'Aircraft Hijacking' },
'7600' : { cssClass: 'squawk7600', markerColor: 'rgb(0, 255, 255)', text: 'Radio Failure' },
'7700' : { cssClass: 'squawk7700', markerColor: 'rgb(255, 255, 0)', text: 'General Emergency' }
};
// Get current map settings
var CenterLat, CenterLon, ZoomLvl, MapType, SiteCirclesCount, SiteCirclesBaseDistance, SiteCirclesInterval;
var SkyAwareVersion = "unknown version";
var RefreshInterval = 1000;
var PlaneRowTemplate = null;
var TrackedAircraft = 0;
var TrackedAircraftPositions = 0;
var TrackedHistorySize = 0;
var SitePosition = null;
var LastReceiverTimestamp = 0;
var StaleReceiverCount = 0;
var FetchPending = null;
var FetchPending_UAT = null;
var MessageCountHistory = [];
var MessageCountHistory_UAT = [];
var MessageRate = 0;
var UatMessageRate = 0;
var NBSP='\u00a0';
var layers;
var layerGroup;
var ActiveFilterCount = 0;
var altitude_slider = null;
var speed_slider = null;
var AircraftLabels = false;
// piaware vs flightfeeder
var isFlightFeeder = false;
var checkbox_div_map = new Map ([
['#icao_col_checkbox', '#icao'],
['#flag_col_checkbox', '#flag'],
['#ident_col_checkbox', '#flight'],
['#reg_col_checkbox', '#registration'],
['#ac_col_checkbox', '#aircraft_type'],
['#squawk_col_checkbox', '#squawk'],
['#alt_col_checkbox', '#altitude'],
['#speed_col_checkbox', '#speed'],
['#vrate_col_checkbox', '#vert_rate'],
['#distance_col_checkbox', '#distance'],
['#heading_col_checkbox', '#track'],
['#messages_col_checkbox', '#msgs'],
['#msg_age_col_checkbox', '#seen'],
['#rssi_col_checkbox', '#rssi'],
['#lat_col_checkbox', '#lat'],
['#lon_col_checkbox', '#lon'],
['#datasource_col_checkbox', '#data_source'],
['#airframes_col_checkbox', '#airframes_mode_s_link'],
['#fa_modes_link_checkbox', '#flightaware_mode_s_link'],
['#fa_photo_link_checkbox', '#flightaware_photo_link'],
]);
var DefaultMinMaxFilters = {
'nautical': {min: 0, maxSpeed: 1000, maxAltitude: 65000}, // kt, ft
'metric' : {min: 0, maxSpeed: 1000, maxAltitude: 20000}, // km/h, m
'imperial' : {min: 0, maxSpeed: 600, maxAltitude: 65000} // mph, ft
};
// Update Planes with data in aircraft json
// receiver_source will specify where the aircraft.json originated from (dump1090-fa or skyaware978)
function processReceiverUpdate(data, receiver_source) {
// Loop through all the planes in the data packet
var now = data.now;
var acs = data.aircraft;
if (receiver_source === "skyaware978") {
// Detect stats reset (i.e. if MessageCountHistory array is > 0 and the latest value > the "messages" field in the data packet)
if (MessageCountHistory_UAT.length > 0 && MessageCountHistory_UAT[MessageCountHistory_UAT.length-1].messages > data.messages) {
MessageCountHistory_UAT = [{'time' : MessageCountHistory_UAT[MessageCountHistory_UAT.length-1].time,
'messages' : 0}];
}
// Maintain a 30 second rollinng history of message counts
MessageCountHistory_UAT.push({ 'time' : now, 'messages' : data.messages});
// .. and clean up any old values
if ((now - MessageCountHistory_UAT[0].time) > 30)
MessageCountHistory_UAT.shift();
} else {
// Detect stats reset (i.e. if MessageCountHistory array is > 0 and the latest value > the "messages" field in the data packet)
if (MessageCountHistory.length > 0 && MessageCountHistory[MessageCountHistory.length-1].messages > data.messages) {
MessageCountHistory = [{'time' : MessageCountHistory[MessageCountHistory.length-1].time,
'messages' : 0}];
}
// Maintain a 30 second rollinng history of message counts
MessageCountHistory.push({ 'time' : now, 'messages' : data.messages});
// .. and clean up any old values
if ((now - MessageCountHistory[0].time) > 30)
MessageCountHistory.shift();
}
for (var j=0; j < acs.length; j++) {
var ac = acs[j];
var hex = ac.hex;
var squawk = ac.squawk;
var plane = null;
// Do we already have this plane object in Planes?
// If not make it.
if (Planes[hex]) {
plane = Planes[hex];
} else {
plane = new PlaneObject(hex);
plane.filter = PlaneFilter;
plane.tr = PlaneRowTemplate.cloneNode(true);
if (hex[0] === '~') {
// Non-ICAO address
plane.tr.cells[0].textContent = hex.substring(1);
$(plane.tr).css('font-style', 'italic');
} else {
plane.tr.cells[0].textContent = hex;
}
// set flag image if available
if (ShowFlags && plane.icaorange.flag_image !== null) {
$('img', plane.tr.cells[1]).attr('src', FlagPath + plane.icaorange.flag_image);
$('img', plane.tr.cells[1]).attr('title', plane.icaorange.country);
} else {
$('img', plane.tr.cells[1]).css('display', 'none');
}
plane.tr.addEventListener('click', function(h, evt) {
if (evt.srcElement instanceof HTMLAnchorElement) {
evt.stopPropagation();
return;
}
if (!$("#map_container").is(":visible")) {
showMap();
}
selectPlaneByHex(h, false);
adjustSelectedInfoBlockPosition();
evt.preventDefault();
}.bind(undefined, hex));
plane.tr.addEventListener('dblclick', function(h, evt) {
if (!$("#map_container").is(":visible")) {
showMap();
}
selectPlaneByHex(h, true);
adjustSelectedInfoBlockPosition();
evt.preventDefault();
}.bind(undefined, hex));
Planes[hex] = plane;
PlanesOrdered.push(plane);
}
// Call the function update
plane.updateData(now, ac, receiver_source);
}
}
function fetchData() {
if (ADSB_Enabled) {
if (FetchPending !== null && FetchPending.state() == 'pending') {
// don't double up on fetches, let the last one resolve
return;
}
FetchPending = $.ajax({ url: 'data/aircraft.json',
timeout: 5000,
cache: false,
dataType: 'json' });
FetchPending.done(function(data) {
process_aircraft_json(data, 'dump1090-fa');
});
FetchPending.fail(function(jqxhr, status, error) {
$("#update_error_detail").text("AJAX call failed (" + status + (error ? (": " + error) : "") + "). Maybe dump1090 is no longer running?");
$("#update_error").css('display','block');
});
}
// Fetch UAT if enabled
if (UAT_Enabled) {
if (FetchPending_UAT !== null && FetchPending_UAT.state() == 'pending') {
// don't double up on fetches, let the last one resolve
return;
}
FetchPending_UAT = $.ajax({ url: 'data-978/aircraft.json',
timeout: 5000,
cache: false,
dataType: 'json' });
FetchPending_UAT.done(function(data) {
// Process UAT aircraft.json here
process_aircraft_json(data, 'skyaware978');
});
FetchPending_UAT.fail(function(jqxhr, status, error) {
$("#uat_update_error_detail").text("AJAX call failed (" + status + (error ? (": " + error) : "") + "). Maybe skyaware978 is no longer running?");
$("#uat_update_error").css('display','block');
});
}
}
// Process an aircraft.json and update Planes.
// receiver_source will specify where the aircraft.json originated from (dump1090-fa or skyaware978)
function process_aircraft_json(data, receiver_source) {
var now = data.now;
processReceiverUpdate(data, receiver_source);
// update timestamps, visibility, history track for all planes - not only those updated
for (var i = 0; i < PlanesOrdered.length; ++i) {
var plane = PlanesOrdered[i];
plane.updateTick(now, LastReceiverTimestamp);
}
selectNewPlanes();
refreshTableInfo();
refreshSelected();
refreshHighlighted();
// Check for stale receiver data
if (LastReceiverTimestamp === now) {
StaleReceiverCount++;
if (StaleReceiverCount > 5) {
$("#update_error_detail").text("The data from dump1090 hasn't been updated in a while. Maybe dump1090 is no longer running?");
$("#update_error").css('display','block');
}
} else {
StaleReceiverCount = 0;
LastReceiverTimestamp = now;
$("#update_error").css('display','none');
}
}
var PositionHistorySize = 0;
var UatPositionHistorySize = 0;
function initialize() {
// Set page basics
document.title = PageName;
flightFeederCheck();
setStatsLink();
PlaneRowTemplate = document.getElementById("plane_row_template");
refreshClock();
$("#loader").removeClass("hidden");
if (ExtendedData || window.location.hash == '#extended') {
$("#extendedData").removeClass("hidden");
}
// Set up map/sidebar splitter
$("#sidebar_container").resizable({
handles: {
w: '#splitter'
},
minWidth: 350
});
// Set up datablock splitter
$('#selected_infoblock').resizable({
handles: {
s: '#splitter-infoblock'
},
containment: "#sidebar_container",
minHeight: 50
});
$('#close-button').on('click', function() {
if (SelectedPlane !== null) {
var selectedPlane = Planes[SelectedPlane];
SelectedPlane = null;
selectedPlane.selected = null;
selectedPlane.clearLines();
selectedPlane.updateMarker();
refreshSelected();
refreshHighlighted();
$('#selected_infoblock').hide();
}
});
// this is a little hacky, but the best, most consitent way of doing this. change the margin bottom of the table container to the height of the overlay
$('#selected_infoblock').on('resize', function() {
$('#sidebar_canvas').css('margin-bottom', $('#selected_infoblock').height() + 'px');
});
// look at the window resize to resize the pop-up infoblock so it doesn't float off the bottom or go off the top
$(window).on('resize', function() {
var topCalc = ($(window).height() - $('#selected_infoblock').height() - 60);
// check if the top will be less than zero, which will be overlapping/off the screen, and set the top correctly.
if (topCalc < 0) {
topCalc = 0;
$('#selected_infoblock').css('height', ($(window).height() - 60) +'px');
}
$('#selected_infoblock').css('top', topCalc + 'px');
});
// to make the infoblock responsive
$('#sidebar_container').on('resize', function() {
if ($('#sidebar_container').width() < 500) {
$('#selected_infoblock').addClass('infoblock-container-small');
} else {
$('#selected_infoblock').removeClass('infoblock-container-small');
}
});
// Set up event handlers for buttons
$("#toggle_sidebar_button").click(toggleSidebarVisibility);
$("#expand_sidebar_button").click(expandSidebar);
$("#show_map_button").click(showMap);
// Set initial element visibility
$("#show_map_button").hide();
$("#range_ring_column").hide();
setColumnVisibility();
// Initialize other controls
initializeUnitsSelector();
// check if the altitude color values are default to enable the altitude filter
if (ColorByAlt.air.h.length === 3 && ColorByAlt.air.h[0].alt === 2000 && ColorByAlt.air.h[0].val === 20 && ColorByAlt.air.h[1].alt === 10000 && ColorByAlt.air.h[1].val === 140 && ColorByAlt.air.h[2].alt === 40000 && ColorByAlt.air.h[2].val === 300) {
customAltitudeColors = false;
}
create_filter_sliders();
$("#aircraft_type_filter_form").submit(onFilterByAircraftType);
$("#aircraft_type_filter_reset_button").click(onResetAircraftTypeFilter);
$("#aircraft_ident_filter_form").submit(onFilterByAircraftIdent);
$("#aircraft_ident_filter_reset_button").click(onResetAircraftIdentFilter);
$('#settingsCog').on('click', function() {
$('#settings_infoblock').toggle();
});
$('#settings_close').on('click', function() {
$('#settings_infoblock').hide();
});
$('#groundvehicle_filter').on('click', function() {
filterGroundVehicles(true);
refreshSelected();
refreshHighlighted();
refreshTableInfo();
});
$('#blockedmlat_filter').on('click', function() {
filterBlockedMLAT(true);
refreshSelected();
refreshHighlighted();
refreshTableInfo();
});
$('#grouptype_checkbox').on('click', function() {
toggleGroupByDataType(true);
});
$('#aircraft_label_checkbox').on('click', function() {
toggleAircraftLabels(true);
});
$('#altitude_checkbox').on('click', function() {
toggleAltitudeChart(true);
});
$('#selectall_checkbox').on('click', function() {
toggleAllPlanes(true);
})
$('#select_all_column_checkbox').on('click', function() {
toggleAllColumns(true);
})
$('#adsb_datasource_checkbox').on('click', function() {
toggleADSBAircraft(true);
refreshDataSourceFilters();
})
$('#uat_datasource_checkbox').on('click', function() {
toggleUATAircraft(true);
refreshDataSourceFilters();
})
$('#mlat_datasource_checkbox').on('click', function() {
toggleMLATAircraft(true);
refreshDataSourceFilters();
})
$('#other_datasource_checkbox').on('click', function() {
toggleOtherAircraft(true);
refreshDataSourceFilters();
})
$('#tisb_datasource_checkbox').on('click', function() {
toggleTISBAircraft(true);
refreshDataSourceFilters();
})
$('#column_select_button').on('click', function() {
this.classList.toggle("config_button_active");
$('#column_select_panel').toggle();
});
$('#filter_button').on('click', function() {
this.classList.toggle("config_button_active");
$('#filter_panel').toggle();
});
$('#stats_page_button').on('click', function() {
if (myAdsbStatsSiteUrl) {
window.open(myAdsbStatsSiteUrl);
}
});
// Event handlers for to column checkboxes
checkbox_div_map.forEach(function (checkbox, div) {
$(div).on('click', function() {
toggleColumn(checkbox, div, true);
});
});
// Force map to redraw if sidebar container is resized - use a timer to debounce
var mapResizeTimeout;
$("#sidebar_container").on("resize", function() {
clearTimeout(mapResizeTimeout);
mapResizeTimeout = setTimeout(updateMapSize, 10);
});
// Initialize settings from local storage
filterGroundVehicles(false);
filterBlockedMLAT(false);
toggleAltitudeChart(false);
toggleAllPlanes(false);
toggleGroupByDataType(false);
toggleAircraftLabels(false);
toggleAllColumns(false);
toggleADSBAircraft(false);
toggleUATAircraft(false);
toggleMLATAircraft(false);
toggleOtherAircraft(false);
toggleTISBAircraft(false);
refreshDataSourceFilters();
// Get 978 receiver metadata if present
$.ajax({ url: 'data-978/receiver.json',
timeout: 5000,
cache: false,
dataType: 'json' })
.done(function(data) {
console.log('SkyAware978 enabled')
UAT_Enabled = true;
UatPositionHistorySize = data.history;
})
.fail(function(data) {
console.warn('Error reading SkyAware978 receiver.json. SkyAware978 may be disabled')
UAT_Enabled = false;
});
// Get receiver metadata, reconfigure using it, then continue
// with initialization
$.ajax({ url: 'data/receiver.json',
timeout: 5000,
cache: false,
dataType: 'json' })
.done(function(data) {
console.log('dump1090-fa enabled');
ADSB_Enabled = true;
if (typeof data.lat !== "undefined") {
SiteShow = true;
SiteLat = data.lat;
SiteLon = data.lon;
DefaultCenterLat = data.lat;
DefaultCenterLon = data.lon;
}
SkyAwareVersion = data.version;
RefreshInterval = data.refresh;
PositionHistorySize = data.history;
})
.fail(function(data) {
console.warn('Error reading dump1090-fa receiver.json. dump1090-fa may be disabled');
ADSB_Enabled = false;
})
.always(function() {
initialize_map();
start_load_history();
});
}
function create_filter_sliders() {
var maxAltitude = DefaultMinMaxFilters[DisplayUnits].maxAltitude;
var minAltitude = DefaultMinMaxFilters[DisplayUnits].min;
var maxSpeed = DefaultMinMaxFilters[DisplayUnits].maxSpeed;
var minSpeed = DefaultMinMaxFilters[DisplayUnits].min;
altitude_slider = document.getElementById('altitude_slider');
noUiSlider.create(altitude_slider, {
start: [minAltitude, maxAltitude],
connect: true,
range: {
'min': minAltitude,
'max': maxAltitude
},
step: 25,
format: {
to: (v) => parseFloat(v).toFixed(0),
from: (v) => parseFloat(v).toFixed(0)
}
});
// Change text to reflect slider values
var minAltitudeInput = document.getElementById('minAltitudeText'),
maxAltitudeInput = document.getElementById('maxAltitudeText');
altitude_slider.noUiSlider.on('update', function (values, handle) {
if (handle) {
maxAltitudeInput.innerHTML = values[handle];
} else {
minAltitudeInput.innerHTML = values[handle];
}
});
// 'Set' event - Whenever a slider is changed to a new value, this event is fired. This function will trigger every time a slider stops changing, including after calls to the .set() method. This event can be considered as the 'end of slide'.
altitude_slider.noUiSlider.on('set', function (values, handle) {
onFilterByAltitude();
});
speed_slider = document.getElementById('speed_slider');
noUiSlider.create(speed_slider, {
start: [minSpeed, maxSpeed],
connect: true,
range: {
'min': minSpeed,
'max': maxSpeed
},
step: 5,
format: {
to: (v) => parseFloat(v).toFixed(0),
from: (v) => parseFloat(v).toFixed(0)
}
});
// Change text to reflect slider values
var minSpeedInput = document.getElementById('minSpeedText'),
maxSpeedInput = document.getElementById('maxSpeedText');
speed_slider.noUiSlider.on('update', function (values, handle) {
if (handle) {
maxSpeedInput.innerHTML = values[handle];
} else {
minSpeedInput.innerHTML = values[handle];
}
});
// 'Set' event - Whenever a slider is changed to a new value, this event is fired. This function will trigger every time a slider stops changing, including after calls to the .set() method. This event can be considered as the 'end of slide'.
speed_slider.noUiSlider.on('set', function (values, handle) {
onFilterBySpeed();
});
}
function reset_filter_sliders() {
var maxAltitude = DefaultMinMaxFilters[DisplayUnits].maxAltitude;
var minAltitude = DefaultMinMaxFilters[DisplayUnits].min;
var maxSpeed = DefaultMinMaxFilters[DisplayUnits].maxSpeed;
var minSpeed = DefaultMinMaxFilters[DisplayUnits].min;
altitude_slider.noUiSlider.updateOptions({
start: [minAltitude, maxAltitude],
range: {
'min': minAltitude,
'max': maxAltitude
}
});
speed_slider.noUiSlider.updateOptions({
start: [minSpeed, maxSpeed],
range: {
'min': minSpeed,
'max': maxSpeed
}
});
// Update filters
updatePlaneFilter();
}
var CurrentHistoryFetch = 0;
var PositionHistoryBuffer = [];
var HistoryItemsReturned = 0;
var TotalPositionHistorySize = 0;
function start_load_history() {
let url = new URL(window.location.href);
let params = new URLSearchParams(url.search);
// Get total number of history.json files to load
TotalPositionHistorySize = PositionHistorySize + UatPositionHistorySize;
if (TotalPositionHistorySize > 0 && params.get('nohistory') !== 'true') {
$("#loader_progress").attr('max', TotalPositionHistorySize);
console.log("Starting to load history (" + TotalPositionHistorySize + " items)");
// Load dump1090 history.json files
for (var i = 0; i < PositionHistorySize; i++) {
load_history_item(i, 'data');
CurrentHistoryFetch++;
}
// Load skyaware978 history.json files
for (var i = 0; i < UatPositionHistorySize; i++) {
load_history_item(i, 'data-978');
CurrentHistoryFetch++;
}
} else {
// Nothing to load
end_load_history();
}
}
// Loads a history json file
function load_history_item(i, source) {
var historyfile = 'history_' + i + '.json';
console.log('Loading ' + source + ' ' + historyfile);
$("#loader_progress").attr('value', CurrentHistoryFetch);
var receiver_source = (source == "data-978" ? "skyaware978" : "dump1090-fa");
$.ajax({ url: source + '/' + historyfile,
timeout: 5000,
cache: false,
dataType: 'json' })
.done(function(data) {
// Tag history.json files with the source we fetched from (/data or /data-978)
data["source"] = receiver_source;
PositionHistoryBuffer.push(data);
HistoryItemsReturned++;
if (HistoryItemsReturned == TotalPositionHistorySize) {
// End load history when all files have been loaded
end_load_history();
}
})
.fail(function(jqxhr, status, error) {
//Doesn't matter if it failed, we'll just be missing a data point
HistoryItemsReturned++;
if (HistoryItemsReturned == TotalPositionHistorySize) {
// End load history when all files have been loaded
end_load_history();
}
});
}
function end_load_history() {
$("#loader").addClass("hidden");
console.log("Done loading history");
if (PositionHistoryBuffer.length > 0) {
var now, last=0;
// Sort history by timestamp
console.log("Sorting history");
PositionHistoryBuffer.sort(function(x,y) { return (x.now - y.now); });
// Process history
for (var h = 0; h < PositionHistoryBuffer.length; ++h) {
now = PositionHistoryBuffer[h].now;
console.log("Applying history " + (h + 1) + "/" + PositionHistoryBuffer.length + " at: " + now);
processReceiverUpdate(PositionHistoryBuffer[h], PositionHistoryBuffer[h].source);
// Update track
console.log("Updating tracks at: " + now);
for (var i = 0; i < PlanesOrdered.length; ++i) {
var plane = PlanesOrdered[i];
plane.updateTrack(now, last);
}
last = now;
}
// Final pass to update all planes to their latest state
console.log("Final history cleanup pass");
for (var i = 0; i < PlanesOrdered.length; ++i) {
var plane = PlanesOrdered[i];
plane.updateTick(now);
}
LastReceiverTimestamp = last;
}
PositionHistoryBuffer = null;
console.log("Completing init");
refreshTableInfo();
refreshSelected();
refreshHighlighted();
reaper();
// Setup our timer to poll from the server.
window.setInterval(fetchData, RefreshInterval);
window.setInterval(reaper, 60000);
// And kick off one refresh immediately.
fetchData();
// update the display layout from any URL query strings
applyUrlQueryStrings();
}
// Function to apply any URL query value to the map before we start
function applyUrlQueryStrings() {
// if asked, toggle featrues at start
let url = new URL(window.location.href);
let params = new URLSearchParams(url.search);
// be sure we start with a 'clean' layout, but only if we need it
var allOptions = [
'banner',
'altitudeChart',
'aircraftTrails',
'map',
'sidebar',
'zoomOut',
'zoomIn',
'moveNorth',
'moveSouth',
'moveWest',
'moveEast',
'displayUnits',
'rangeRings',
'ringCount',
'ringBaseDistance',
'ringInterval'
]
var needReset = false;
for (var option of allOptions) {
if (params.has(option)) {
needReset = true;
break;
}
}
if (needReset) {
resetMap();
}
if (params.get('banner') === 'hide') {
hideBanner();
}
if (params.get('altitudeChart') === 'hide') {
$('#altitude_checkbox').removeClass('settingsCheckboxChecked');
$('#altitude_chart').hide();
}
if (params.get('altitudeChart') === 'show') {
$('#altitude_checkbox').addClass('settingsCheckboxChecked');
$('#altitude_chart').show();
}
if (params.get('aircraftTrails') === 'show') {
selectAllPlanes();
}
if (params.get('aircraftTrails') === 'hide') {
deselectAllPlanes();
}
if (params.get('map') === 'show') {
showMap();
}
if (params.get('map') === 'hide') {
expandSidebar();
}
if (params.get('sidebar') === 'show') {
$("#sidebar_container").show();
updateMapSize();
}
if (params.get('sidebar') === 'hide') {
$("#sidebar_container").hide();
updateMapSize();
}
if (params.get('zoomOut')) {
zoomMap(params.get('zoomOut'), true);
}
if (params.get('zoomIn')) {
zoomMap(params.get('zoomIn'), false);
}
if (params.get('moveNorth')) {
moveMap(params.get('moveNorth'), true, false);
}
if (params.get('moveSouth')) {
moveMap(params.get('moveSouth'), true, true);
}
if (params.get('moveEast')) {
moveMap(params.get('moveEast'), false, false);
}
if (params.get('moveWest')) {
moveMap(params.get('moveWest'), false, true);
}
if (params.get('displayUnits')) {
setDisplayUnits(params.get('displayUnits'));
}
if (params.get('rangeRings')) {
setRangeRingVisibility(params.get('rangeRings'));
}
if (params.get('ringCount')) {
setRingCount(params.get('ringCount'));
}
if (params.get('ringBaseDistance')) {
setRingBaseDistance(params.get('ringBaseDistance'));
}
if (params.get('ringInterval')) {
setRingInterval(params.get('ringInterval'));
}
}
// Make a LineString with 'points'-number points
// that is a closed circle on the sphere such that the
// great circle distance from 'center' to each point is
// 'radius' meters
function make_geodesic_circle(center, radius, points) {
var angularDistance = radius / 6378137.0;
var lon1 = center[0] * Math.PI / 180.0;
var lat1 = center[1] * Math.PI / 180.0;
var geom;
for (var i = 0; i <= points; ++i) {
var bearing = i * 2 * Math.PI / points;
var lat2 = Math.asin( Math.sin(lat1)*Math.cos(angularDistance) +
Math.cos(lat1)*Math.sin(angularDistance)*Math.cos(bearing) );
var lon2 = lon1 + Math.atan2(Math.sin(bearing)*Math.sin(angularDistance)*Math.cos(lat1),
Math.cos(angularDistance)-Math.sin(lat1)*Math.sin(lat2));
lat2 = lat2 * 180.0 / Math.PI;
lon2 = lon2 * 180.0 / Math.PI;
if (!geom) {
geom = new ol.geom.LineString([[lon2, lat2]]);
} else {
geom.appendCoordinate([lon2, lat2]);
}
}
return geom;
}
// Initalizes the map and starts up our timers to call various functions
function initialize_map() {
// Load stored map settings if present
CenterLat = Number(localStorage['CenterLat']) || DefaultCenterLat;
CenterLon = Number(localStorage['CenterLon']) || DefaultCenterLon;
ZoomLvl = Number(localStorage['ZoomLvl']) || DefaultZoomLvl;
MapType = localStorage['MapType'];
var groupByDataTypeBox = localStorage.getItem('groupByDataType');
// Set SitePosition, initialize sorting
if (SiteShow && (typeof SiteLat !== 'undefined') && (typeof SiteLon !== 'undefined')) {
SitePosition = [SiteLon, SiteLat];
if (groupByDataTypeBox === 'deselected') {
sortByDistance();
}
} else {
SitePosition = null;
PlaneRowTemplate.cells[9].style.display = 'none'; // hide distance column
document.getElementById("distance").style.display = 'none'; // hide distance header
if (groupByDataTypeBox === 'deselected') {
sortByAltitude();
}
}
// Maybe hide flag info
if (!ShowFlags) {
PlaneRowTemplate.cells[1].style.display = 'none'; // hide flag column
document.getElementById("flag").style.display = 'none'; // hide flag header
document.getElementById("infoblock_country").style.display = 'none'; // hide country row
}
// Initialize OL3
layers = createBaseLayers();
var iconsLayer = new ol.layer.Vector({
name: 'ac_positions',
type: 'overlay',
title: 'Aircraft positions',
source: new ol.source.Vector({
features: PlaneIconFeatures,
})
});
var metarLayer = createMetarLayer();
layers.push(new ol.layer.Group({
title: 'Overlays',
layers: [
new ol.layer.Vector({
name: 'site_pos',
type: 'overlay',
title: 'Site position and range rings',
source: new ol.source.Vector({
features: StaticFeatures,
})
}),
new ol.layer.Vector({
name: 'ac_trail',
type: 'overlay',
title: 'Selected aircraft trail',
source: new ol.source.Vector({
features: PlaneTrailFeatures,
})
}),
metarLayer,
iconsLayer
]
}));
var foundType = false;
var baseCount = 0;
layerGroup = new ol.layer.Group({
layers: layers
})
ol.control.LayerSwitcher.forEachRecursive(layerGroup, function(lyr) {
if (!lyr.get('name'))
return;
if (lyr.get('type') === 'base') {
baseCount++;
if (MapType === lyr.get('name')) {
foundType = true;
lyr.setVisible(true);
} else {
lyr.setVisible(false);
}
lyr.on('change:visible', function(evt) {
if (evt.target.getVisible()) {
MapType = localStorage['MapType'] = evt.target.get('name');
createSiteCircleFeatures();
}
});
} else if (lyr.get('type') === 'overlay') {
var visible = localStorage['layer_' + lyr.get('name')];
if (visible != undefined) {
// javascript, why must you taunt me with gratuitous type problems
lyr.setVisible(visible === "true");
}
lyr.on('change:visible', function(evt) {
localStorage['layer_' + evt.target.get('name')] = evt.target.getVisible();
});
}
})