// -*- mode: javascript; indent-tabs-mode: nil; c-basic-offset: 8 -*- "use strict"; // Define our global variables var GoogleMap = null; var Planes = {}; var PlanesOrdered = []; var SelectedPlane = null; var FollowSelected = 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; var Dump1090Version = "unknown version"; var RefreshInterval = 1000; var PlaneRowTemplate = null; var TrackedAircraft = 0; var TrackedAircraftPositions = 0; var TrackedHistorySize = 0; var SitePosition = null; var ReceiverClock = null; var LastReceiverTimestamp = 0; var StaleReceiverCount = 0; var FetchPending = null; var MessageCountHistory = []; var MessageRate = 0; var NBSP='\u00a0'; function processReceiverUpdate(data) { // Loop through all the planes in the data packet var now = data.now; var acs = data.aircraft; // Detect stats reset if (MessageCountHistory.length > 0 && MessageCountHistory[MessageCountHistory.length-1].messages > data.messages) { MessageCountHistory = [{'time' : MessageCountHistory[MessageCountHistory.length-1].time, 'messages' : 0}]; } // Note the message count in the history 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 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.tr = PlaneRowTemplate.cloneNode(true); // Lookup ICAO country flag var hexa = +("0x" + hex); for (var i = 0; i < ICAO_Codes.length; i++) { if ( hexa >= ICAO_Codes[i].start && hexa <= ICAO_Codes[i].end) { plane.Country = ICAO_Codes[i].Country; plane.Flag = '
'; } } // end of flag lookup if (hex[0] === '~') { // Non-ICAO address plane.tr.cells[0].textContent = hex.substring(1); $(plane.tr).css('font-style', 'italic'); plane.tr.cells[1].textContent = (""); } else { plane.tr.cells[0].textContent = (hex); plane.tr.cells[1].innerHTML = (plane.Flag); } plane.tr.addEventListener('click', selectPlaneByHex.bind(undefined,hex,false)); plane.tr.addEventListener('dblclick', selectPlaneByHex.bind(undefined,hex,true)); Planes[hex] = plane; PlanesOrdered.push(plane); } // Call the function update plane.updateData(now, ac); } } function fetchData() { 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) { var now = data.now; processReceiverUpdate(data); // 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); } refreshTableInfo(); refreshSelected(); if (ReceiverClock) { var rcv = new Date(now * 1000); ReceiverClock.render(rcv.getUTCHours(),rcv.getUTCMinutes(),rcv.getUTCSeconds()); } // 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'); } }); 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'); }); } var PositionHistorySize = 0; function initialize() { // Set page basics document.title = PageName; $("#infoblock_name").text(PageName); PlaneRowTemplate = document.getElementById("plane_row_template"); if (!ShowClocks) { $('#timestamps').css('display','none'); } else { // Create the clocks. new CoolClock({ canvasId: "utcclock", skinId: "classic", displayRadius: 40, showSecondHand: true, gmtOffset: "0", // this has to be a string! showDigital: false, logClock: false, logClockRev: false }); ReceiverClock = new CoolClock({ canvasId: "receiverclock", skinId: "classic", displayRadius: 40, showSecondHand: true, gmtOffset: null, showDigital: false, logClock: false, logClockRev: false }); // disable ticking on the receiver clock, we will update it ourselves ReceiverClock.tick = (function(){}) } $("#loader").removeClass("hidden"); // Get receiver metadata, reconfigure using it, then continue // with initialization $.ajax({ url: 'data/receiver.json', timeout: 5000, cache: false, dataType: 'json' }) .done(function(data) { if (typeof data.lat !== "undefined") { SiteShow = true; SiteLat = data.lat; SiteLon = data.lon; DefaultCenterLat = data.lat; DefaultCenterLon = data.lon; } Dump1090Version = data.version; RefreshInterval = data.refresh; PositionHistorySize = data.history; }) .always(function() { initialize_map(); start_load_history(); }); } var CurrentHistoryFetch = null; var PositionHistoryBuffer = [] function start_load_history() { if (PositionHistorySize > 0) { $("#loader_progress").attr('max',PositionHistorySize); console.log("Starting to load history (" + PositionHistorySize + " items)"); load_history_item(0); } else { end_load_history(); } } function load_history_item(i) { if (i >= PositionHistorySize) { end_load_history(); return; } console.log("Loading history #" + i); $("#loader_progress").attr('value',i); $.ajax({ url: 'data/history_' + i + '.json', timeout: 5000, cache: false, dataType: 'json' }) .done(function(data) { PositionHistoryBuffer.push(data); load_history_item(i+1); }) .fail(function(jqxhr, status, error) { // No more history 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 + "/" + PositionHistoryBuffer.length + " at: " + now); processReceiverUpdate(PositionHistoryBuffer[h]); // update track console.log("Updating tracks at: " + now); for (var i = 0; i < PlanesOrdered.length; ++i) { var plane = PlanesOrdered[i]; plane.updateTrack((now - last) + 1); } 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(); reaper(); // Setup our timer to poll from the server. window.setInterval(fetchData, RefreshInterval); window.setInterval(reaper, 60000); // And kick off one refresh immediately. fetchData(); } // 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; // Set SitePosition, initialize sorting if (SiteShow && (typeof SiteLat !== 'undefined') && (typeof SiteLon !== 'undefined')) { SitePosition = new google.maps.LatLng(SiteLat, SiteLon); sortByDistance(); } else { SitePosition = null; PlaneRowTemplate.cells[5].style.display = 'none'; // hide distance column document.getElementById("distance").style.display = 'none'; // hide distance header sortByAltitude(); } // Make a list of all the available map IDs var mapTypeIds = []; for(var type in google.maps.MapTypeId) { mapTypeIds.push(google.maps.MapTypeId[type]); } // Push OSM on to the end mapTypeIds.push("OSM"); mapTypeIds.push("dark_map"); // Styled Map to outline airports and highways var styles = [ { "featureType": "administrative", "stylers": [ { "visibility": "off" } ] },{ "featureType": "landscape", "stylers": [ { "visibility": "off" } ] },{ "featureType": "poi", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road", "stylers": [ { "visibility": "off" } ] },{ "featureType": "transit", "stylers": [ { "visibility": "off" } ] },{ "featureType": "landscape", "stylers": [ { "visibility": "on" }, { "weight": 8 }, { "color": "#000000" } ] },{ "featureType": "water", "stylers": [ { "lightness": -74 } ] },{ "featureType": "transit.station.airport", "stylers": [ { "visibility": "on" }, { "weight": 8 }, { "invert_lightness": true }, { "lightness": 27 } ] },{ "featureType": "road.highway", "stylers": [ { "visibility": "simplified" }, { "invert_lightness": true }, { "gamma": 0.3 } ] },{ "featureType": "road", "elementType": "labels", "stylers": [ { "visibility": "off" } ] } ] // Add our styled map var styledMap = new google.maps.StyledMapType(styles, {name: "Dark Map"}); // Define the Google Map var mapOptions = { center: new google.maps.LatLng(CenterLat, CenterLon), zoom: ZoomLvl, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: true, streetViewControl: false, mapTypeControlOptions: { mapTypeIds: mapTypeIds, position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU } }; GoogleMap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); //Define OSM map type pointing at the OpenStreetMap tile server GoogleMap.mapTypes.set("OSM", new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png"; }, tileSize: new google.maps.Size(256, 256), name: "OpenStreetMap", maxZoom: 18 })); GoogleMap.mapTypes.set("dark_map", styledMap); // Listeners for newly created Map google.maps.event.addListener(GoogleMap, 'center_changed', function() { localStorage['CenterLat'] = GoogleMap.getCenter().lat(); localStorage['CenterLon'] = GoogleMap.getCenter().lng(); if (FollowSelected) { // On manual navigation, disable follow var selected = Planes[SelectedPlane]; if (Math.abs(GoogleMap.getCenter().lat() - selected.position.lat()) > 0.0001 && Math.abs(GoogleMap.getCenter().lng() - selected.position.lng()) > 0.0001) { FollowSelected = false; refreshSelected(); } } }); google.maps.event.addListener(GoogleMap, 'zoom_changed', function() { localStorage['ZoomLvl'] = GoogleMap.getZoom(); }); // Add home marker if requested if (SitePosition) { var markerImage = new google.maps.MarkerImage( 'http://maps.google.com/mapfiles/kml/pal4/icon57.png', new google.maps.Size(32, 32), // Image size new google.maps.Point(0, 0), // Origin point of image new google.maps.Point(16, 16)); // Position where marker should point var marker = new google.maps.Marker({ position: SitePosition, map: GoogleMap, icon: markerImage, title: SiteName, zIndex: -99999 }); if (SiteCircles) { for (var i=0;i