-
Notifications
You must be signed in to change notification settings - Fork 7
/
test.js
2912 lines (2705 loc) · 101 KB
/
test.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
/*
* Copyright (C) 2017 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*/
var geoMode = 0;
requirejs.config({
waitSeconds: 180,
paths: {
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min",
"jqueryui": "https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/" +
"jquery-ui.min",
"jquery-csv": "https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.8.3/" +
"jquery.csv",
"simple-stats": "https://unpkg.com/[email protected]/dist/" +
"simple-statistics.min",
"regression": "src/regression/regression",
"resizejs": "js/resizejs/src/ResizeSensor"
}
});
requirejs(['./src/WorldWind',
'./LayerManager', 'src/countries/DataLayer',
'src/countries/GlobalDataPoint',
'src/array/DataArray',
'src/customlayer/LayerPoint',
'jquery',
'jqueryui', 'jquery-csv', 'simple-stats', 'regression', 'resizejs'
],
function(ww,
LayerManager, DataLayer, GlobalDataPoint, DataArray, LayerPoint,
ResizeSensor) {
"use strict";
var ResizeSensor = require("resizejs");
//Basic configuration
WorldWind.Logger.setLoggingLevel(WorldWind.Logger.LEVEL_WARNING);
WorldWind.configuration.baseUrl = '';
var wwd = new WorldWind.WorldWindow("canvasOne");
//Loading the files (raw data)
var countryData =
new DataArray(loadCSVData('csvdata/countries.csv'), {});
var stationData =
new DataArray(loadCSVData('csvdata/weatherstations.csv'), {});
var agriDef = new DataArray(loadCSVData('csvdata/cropAcros.csv'));
var csvMultiData = loadCSVDataArray();
var agriData = new DataArray(convertArrayToDataSet(csvMultiData[0]), {
HTML_ID: 'agri',
HTML_Label: 'Ag. Production Data List',
definitions: agriDef,
searchName: 'crop production',
units: ' Production in tonnes'
});
var atmoData = new DataArray(convertArrayToDataSet(csvMultiData[1]), {
HTML_ID: 'atmo',
HTML_Label: ' Crops'
});
var priceData = new DataArray(convertArrayToDataSet(csvMultiData[2]), {
HTML_ID: 'price',
HTML_Label: 'Price Data List',
searchName: 'prices'
});
var liveData = new DataArray(convertArrayToDataSet(csvMultiData[3]), {
HTML_ID: 'live',
HTML_Label: 'Livestock Data List',
searchName: 'livestock'
});
var emissionAgriData = new DataArray(
convertArrayToDataSet(csvMultiData[4]), {
HTML_ID: 'emission',
HTML_Label: 'Emission Data List',
searchName: 'emission output type'
});
var atmoDataMonthly = new DataArray(convertArrayToDataSet(csvMultiData[5]), {
HTML_ID: 'atmoMonth',
HTML_Label: 'Monthly Atmo List'
});
var pestiData = new DataArray(convertArrayToDataSet(csvMultiData[6]), {
HTML_ID: 'pesti',
HTML_Label: 'Pesticide Data List',
searchName: 'crop production'
});
var fertiData = new DataArray(convertArrayToDataSet(csvMultiData[7]), {
HTML_ID: 'ferti',
HTML_Label: 'Fertilizer Data List',
searchName: 'fertiliser use'
});
var yieldData = new DataArray(convertArrayToDataSet(csvMultiData[8]), {
HTML_ID: 'yield',
HTML_Label: 'Yield Data List',
searchName: 'yield output'
});
var refugeeData = new DataArray(convertArrayToDataSet(csvMultiData[9]));
agriData.options.subData = [refugeeData.values];
atmoData.options.subData = [agriData.values];
var countryButtonDataArray = [agriData, priceData, liveData, emissionAgriData,
pestiData, fertiData, yieldData
];
var stationButtonArray = [atmoData, atmoDataMonthly];
var geoJSONData = loadGEOJsonData('./geo/data/countries.geojson');
var layers = [{
layer: new WorldWind.BMNGLayer(),
enabled: false
},
{
layer: new WorldWind.BMNGLandsatLayer(),
enabled: false
},
{
layer: new WorldWind.BingAerialLayer(null),
enabled: false
},
{
layer: new WorldWind.BingAerialWithLabelsLayer(null),
enabled: true
},
{
layer: new WorldWind.BingRoadsLayer(null),
enabled: false
},
{
layer: new WorldWind.CompassLayer(),
enabled: false
},
{
layer: new WorldWind.CoordinatesDisplayLayer(wwd),
enabled: true
},
{
layer: new WorldWind.ViewControlsLayer(wwd),
enabled: true
},
];
for (var l = 0; l < layers.length; l++) {
layers[l].layer.enabled = layers[l].enabled;
wwd.addLayer(layers[l].layer);
}
// Create a layer manager for controlling layer visibility.
var layerManager = new LayerManager(wwd);
////////////////////////////////////////////////////////////////////////
//Layer Loading
////////////////////////////////////////////////////////////////////////
loadCountryLayer(wwd, countryData);
loadWeatherLayer(wwd, stationData);
var rainfallLayer =
new LayerPoint("https://neowms.sci.gsfc.nasa.gov/wms/wms",
"TRMM_3B43M");
var seaSurfaceLayer =
new LayerPoint("https://neowms.sci.gsfc.nasa.gov/wms/wms",
"MYD28M");
var landSurfaceDay =
new LayerPoint("https://neowms.sci.gsfc.nasa.gov/wms/wms",
"MOD11C1_D_LSTDA");
var landSurfaceNight =
new LayerPoint("https://neowms.sci.gsfc.nasa.gov/wms/wms",
"MOD11C1_D_LSTNI");
var trueColour =
new LayerPoint("https://neowms.sci.gsfc.nasa.gov/wms/wms",
"MOD_143D_RR");
var WMSTLayerArray = [];
WMSTLayerArray.push(rainfallLayer);
WMSTLayerArray.push(seaSurfaceLayer);
WMSTLayerArray.push(landSurfaceDay);
WMSTLayerArray.push(landSurfaceNight);
WMSTLayerArray.push(trueColour);
var i = 0;
var WMSTLayers = [];
for (i = 0; i < WMSTLayerArray.length; i++) {
WMSTLayers.push(
loadWMSTLayers(wwd, layerManager, WMSTLayerArray[i], i));
}
layerManager.synchronizeLayerList();
var starFieldLayer = new WorldWind.StarFieldLayer();
var atmosphereLayer = new WorldWind.AtmosphereLayer();
//IMPORTANT: add the starFieldLayer before the atmosphereLayer
wwd.addLayer(starFieldLayer);
wwd.addLayer(atmosphereLayer);
var sunSimulationCheckBox = document.getElementById(
'stars-simulation');
var doRunSimulation = false;
var timeStamp = Date.now();
var factor = 1;
sunSimulationCheckBox.addEventListener('change', onSunCheckBoxClick,
false);
function onSunCheckBoxClick() {
doRunSimulation = this.checked;
if (!doRunSimulation) {
starFieldLayer.time = new Date();
atmosphereLayer.lightLocation =
WorldWind.SunPosition.getAsGeographicLocation(starFieldLayer.time);
}
wwd.redraw();
}
function runSunSimulation(wwd, stage) {
if (stage === WorldWind.AFTER_REDRAW && doRunSimulation) {
timeStamp += (factor * 60 * 1000);
starFieldLayer.time = new Date(timeStamp);
atmosphereLayer.lightLocation =
WorldWind.SunPosition.getAsGeographicLocation(starFieldLayer.time);
wwd.redraw();
}
}
////////////////////////////////////////////////////////////////////////
//Event Listening
////////////////////////////////////////////////////////////////////////
var highlightedItems = [];
var handlePick = function(x, y) {
//Handle a pick (only placemarks shall be)
// De-highlight any previously highlighted placemarks.
for (var h = 0; h < highlightedItems.length; h++) {
highlightedItems[h].highlighted = false;
}
highlightedItems = [];
var pickList;
pickList = wwd.pick(wwd.canvasCoordinates(x, y));
if (pickList.objects.length > 0) {
var i = 0;
for (i = 0; i < pickList.objects.length; i++) {
pickList.objects[i].userObject.highlighted = true;
// Keep track of highlighted items in order to
// de-highlight them later.
highlightedItems.push(pickList.objects[i].userObject);
if (typeof(pickList.objects[i].userObject.type) !=
'undefined') {
//It's most likely a placemark
//"most likely"
//Grab the co-ordinates
var placeLat =
pickList.objects[i].userObject.position.latitude;
var placeLon =
pickList.objects[i].userObject.position.longitude;
//Find the country
if (pickList.objects[i].userObject.type == 'Countries') {
generateCountryTab(countryButtonDataArray,
countryData, placeLat, placeLon);
} else if (pickList.objects[i].userObject.type ==
'Weather Station') {
generateStationTab(stationButtonArray, stationData,
placeLat, placeLon, countryData);
}
}
}
}
};
// Set up to handle clicks and taps.
var handleClick = function(recognizer) {
// Obtain the event location.
var x = recognizer.clientX,
y = recognizer.clientY;
// Perform the pick. Must first convert from window coordinates
// to canvas coordinates, which are
// relative to the upper left corner of the canvas rather than
// the upper left corner of the page.
var pickList = wwd.pick(wwd.canvasCoordinates(x, y));
// If only one thing is picked and it is the terrain, tell the
// world window to go to the picked location.
var i = 0;
for (i = 0; i < pickList.objects.length; i++) {
if (pickList.objects[i].isTerrain) {
var position = pickList.objects[i].position;
wwd.goTo(new WorldWind.Location(position.latitude,
position.longitude));
}
}
handlePick(x, y);
};
// Listen for mouse clicks.
var clickRecognizer = new WorldWind.ClickRecognizer(wwd, handleClick);
// Listen for taps on mobile devices.
var tapRecognizer = new WorldWind.TapRecognizer(wwd, handleClick);
////////////////////////////////////////////////////////////////////////
//Tab Generations
////////////////////////////////////////////////////////////////////////
generateWeatherHTML(countryData);
giveWeatherButtonFunctionality();
//Generate regression comparison and the provide functionality
//In theory we could use any data we want
generateGeoComparisonButton(agriData);
giveGeoComparisonFunctionality(agriData, geoJSONData, wwd,
layerManager);
generateRemoveButton();
//Initiate with a hardcoded link
generateCountryTab(countryButtonDataArray, countryData, 64, 26);
////////////////////////////////////////////////////////////////////////
// Helper Functions
////////////////////////////////////////////////////////////////////////
/**
* Loads all CSV Files
* @param {String} csvAddress contains the address of the csvFile
* @returns {Array<Object>} The object fields are based on the
* headings in the csv file.
*/
function loadCSVData(csvAddress) {
//Find the file
var csvString = "";
var csvData = [];
var i = 0;
var csvRequest = $.ajax({
async: false,
url: csvAddress,
success: function(file_content) {
csvString = file_content;
csvData = $.csv.toObjects(csvString);
}
});
return csvData;
}
/**
* Loads weather stations CSV Data Array into Array of Weather Stations
* @param {DataArray} csvData contains the weather station location and
* details.
* @returns {Array<GlobalDataPoint>} A datastructure that maps a value
* to a location.
*/
function loadWeatherStation(csvData) {
var i = 0;
var temp = [];
for (i = 0; i < csvData.values.length; i++) {
temp.push(new GlobalDataPoint(csvData.values[i].stationName,
csvData.values[i].lat, csvData.values[i].lon, {
icon_code: '',
type: 'Weather Station'
}));
}
return temp;
}
/**
* Loads the weather station layer
* @param {WorldWindow} wwd is the world window of the globe
* @param {Array<DataLayer>} weatherDataArray is
* an array containing the WMS Layers that needs to be loaded
*/
function loadWeatherLayer(wwd, weatherDataArray) {
var weatherLayer = new DataLayer('Weather Station');
var weatherData = loadWeatherStation(weatherDataArray);
weatherLayer.loadFlags(weatherData, 'images/sun', '.png',
null, null);
console.log(weatherLayer);
wwd.addLayer(weatherLayer.layer);
}
/**
* Loads country CSV Data Array into Array of Countries
* @param {DataArray} countryDataArray DataArray that contains data of
* where the countries are located (centre-based).
* @returns {Array} temp is an array containing all
* countries
*/
function loadCountries(countryDataArray) {
var i = 0;
var temp = [];
for (i = 0; i < countryDataArray.values.length; i++) {
temp.push(new GlobalDataPoint(countryDataArray.values[i].country,
countryDataArray.values[i].lat,
countryDataArray.values[i].lon, {
code_2: countryDataArray.values[i].code2,
code_3: countryDataArray.values[i].code3,
icon_code: countryDataArray.values[i].iconCode,
name: countryDataArray.values[i].country,
type: 'Country'
}));
}
return temp;
}
/**
* Loads the country layer
* @param {WorldWindow} wwd is the window to draw the things on.
* @param {DataArray} countryDataArray is
* the data array containing where the flags need to be placed
* @returns {DataLayer} an object containing the layer and other details
* such as configuration of the layer
*/
function loadCountryLayer(wwd, countryDataArray) {
var countryLayer = new DataLayer('Countries');
var countryData = loadCountries(countryDataArray);
countryLayer.loadFlags(countryData, './flags/', '.png', null, null);
wwd.addLayer(countryLayer.layer);
return countryLayer;
}
/**
* hardcoded link: loads appropriate geoJSON data
* @param {string} geoJSONAddress address where the geoJSON file is at.
* @returns {Object} contains details of the country borders in object
* format.
*/
function loadGEOJsonData(geoJSONAddress) {
//Load GEOJSON
var data;
$.ajax({
dataType: 'json',
async: false,
url: geoJSONAddress,
success: function(file_content) {
data = file_content;
},
fail: function() {}
});
//Change the ISO name to code3
var i = 0;
for (i = 0; i < data.features.length; i++) {
data.features[i].properties.code3 =
data.features[i].properties.ISO_A3;
delete data.features[i].properties.ISO_A3;
data.features[i].properties.name =
data.features[i].properties.ADMIN;
delete data.features[i].properties.ADMIN;
}
return data;
}
/**
* Generates the html for the weather search
* @param {DataArray} countryDataArray of data containing the country
* codes to be loaded onto the HTML
*/
function generateWeatherHTML(countryDataArray) {
var countryData = loadCountries(countryDataArray);
var weatherHTML = '<h5 class="smallerfontsize">Weather Search</h5>';
weatherHTML += '<p><input type="text" class="form-control" ' +
'id="cityInput" placeholder="Search for city" title=' +
'"Type in a layer"></p>';
weatherHTML += '<select id="countryNames" class="form-control">'
var i = 0;
for (i = 0; i < countryData.length; i++) {
//console.log(countryData);
weatherHTML += '<option>' + countryData[i].options.code_2 + ' - ' +
countryData[i].name + '</option>';
}
weatherHTML += '</select><br>';
weatherHTML += '<p><button class="btn-info" id="searchWeather">' +
'Search Weather</button></p>';
weatherHTML += '<div id="searchDetails"></div>'
$('#weather').append(weatherHTML);
}
/**
* Provides functionality to the weather button. (Hardcoded API Key)
*/
function giveWeatherButtonFunctionality() {
var APIKEY = '26fb68df7323284ea4430d8e4d3c60b1';
var weatherButton = $('#searchWeather').button();
weatherButton.on('click', function() {
//Extract the two inputs
var cityInput = $('#cityInput').val();
var country = $('#countryNames :selected').val();
var countryInput = country.slice(0, 2);
//Make an api request
var apiURL = 'https://api.openweathermap.org/' +
'data/2.5/weather?q=' + cityInput + ',' +
countryInput + '&appid=' + APIKEY;
//Make an ajax request
//Note that api attempst to return the closet result possible
$.ajax({
url: encodeURI(apiURL),
method: 'get',
dataType: 'json',
success: function(data) {
//Create some html
var dropArea = $('#searchDetails');
dropArea.html('');
var tempHTML = '<h5 class="fontsize"><b>Weather' +
' Details for ' + data.name + '</b></h5>';
tempHTML += '<p><b>Country:</b> ' + data.sys.country +
'</p><br>';
tempHTML += '<p><b>Current Outlook:</b> ' +
data.weather[0].main + '</p><br>';
tempHTML += '<p><b>Current Outlook Description:</b> ' +
data.weather[0].description + '</p><br>';
tempHTML += '<p><b>Current Temperature (Celsius):</b> ' +
Math.round((data.main.temp - 272), 2) + '</p><br>';
tempHTML += '<p><b>Sunrise:</b> ' + timeConverter(
data.sys.sunrise) + '</p><br>';
tempHTML += '<p><b>Sunset:</b> ' + timeConverter(
data.sys.sunset) + '</p><br>';
tempHTML += '<p><b>Max Temperature Today (Celsius)' +
':</b> ' + Math.round((data.main.temp_max - 272), 2) +
'</p><br>';
tempHTML += '<p><b>Min Temperature Today (Celsius):' +
'</b> ' + Math.round(data.main.temp_min - 272, 2) +
'</p><br>';
tempHTML += '<p><b>Pressure (HPa):</b> ' +
data.main.pressure + '</p><br>';
tempHTML += '<p><b>Humidity (%):</b> ' +
data.main.humidity + '</p><br>';
tempHTML += '<p><b>Wind speed (m/s):</b>' +
data.wind.speed + '</p><br><br>';
dropArea.append(tempHTML);
},
fail: function() {}
})
});
}
/**
* Checks if the tab should be displayed. Also adds sensors to create
* readjusting graphs.
*/
function checkTabs() {
var allTabs = $('.tab-content > .tab-pane');
var i = 0;
var isDisplay = false;
for (i = 0; i < allTabs.length; i++) {
if ($(allTabs[i]).css('display') != 'none') {
isDisplay = true;
}
}
var resizable = $('.resizable');
if (isDisplay) {
resizable.show();
} else {
resizable.hide();
}
if ($('#wms').css('display') == 'none') {
$('.glyphicon-globe').css('color', 'white');
} else {
$('.glyphicon-globe').css('color', 'lightgreen');
}
if ($('#layers').css('display') == 'none') {
$('.fa-map').css('color', 'white');
} else {
$('.fa-map').css('color', 'lightgreen');
}
if ($('#country').css('display') == 'none') {
$('.glyphicon-flag').css('color', 'white');
} else {
$('.glyphicon-flag').css('color', 'lightgreen');
}
if ($('#station').css('display') == 'none') {
$('.glyphicon-cloud').css('color', 'white');
} else {
$('.glyphicon-cloud').css('color', 'lightgreen');
}
if ($('#graphs').css('display') == 'none') {
$('.fa-area-chart').css('color', 'white');
} else {
$('.fa-area-chart').css('color', 'lightgreen');
}
if ($('#comp').css('display') == 'none') {
$('.glyphicon-briefcase').css('color', 'white');
} else {
$('.glyphicon-briefcase').css('color', 'lightgreen');
}
if ($('#weather').css('display') == 'none') {
$('.fa-sun-o').css('color', 'white');
} else {
$('.fa-sun-o').css('color', 'lightgreen');
}
if ($('#view').css('display') == 'none') {
$('.glyphicon-eye-open').css('color', 'white');
} else {
$('.glyphicon-eye-open').css('color', 'lightgreen');
}
}
$(function() {
$(".draggable").draggable({
containment: "window"
});
});
/**
* Lets the resizable tab to resizable
*/
var tabsFn = (function() {
function init() {
setHeight();
}
function setHeight() {
var $tabPane = $('.tab-pane'),
tabsHeight = $('.resizable').height();
$tabPane.css({
height: tabsHeight
});
}
$(init);
$(".resizable").resizable({
stop: setHeight,
/* animation removed - stops resizing from working
* minHeight and minWidth are set so the UI will not glitch out
*/
maxHeight: 800,
maxWidth: 1400,
minHeight: 250,
minWidth: 280
});
})();
/**
* Gives functionality to the WMST buttons associated with the layers
* the part which lets the controls to be visible and turning on the
* the layer on and off
* @param {number} layerNumber shows which layer is associated
* @param {Layer} layer The layer that will be toggled on and off
*/
function giveWMSTLayersFunctionality(layerNumber, layer) {
$('#layerToggle' + layerNumber).click(function() {
var buttonNumber = this.id.slice('layerToggle'.length);
layer.enabled = !layer.enabled;
var layerControlList = $('.toggleLayers');
var layerNumber = -1;
var k = 0;
for (k = 0; k < layerControlList.length; k++) {
if ($(layerControlList[k]).text().includes($(this).text())) {
layerNumber = k;
break;
}
}
if (layerNumber != -1) {
//Find the button
$(layerControlList[k]).toggle();
}
});
}
/**
* preloads WMST layers
*
* @param {WorldWind} wwd - worldwindow
* @param {LayerManager} layerManager - layerManager from layerManager.js
* @param {LayerPoint} layerPoint -
* The layer itself with other details to display
* @param {number} layerNumber - the number of the layer
* inserted for control purposes
* @returns {WmtsLayer} The WMST Layer that has just been loaded
*/
function loadWMSTLayers(wwd, layerManager, layerPoint, layerNumber) {
// Called asynchronously to parse and create the WMS layer
var createWMTSLayer = function(xmlDom) {
// Create a WmsCapabilities object from the XML DOM
var wms = new WorldWind.WmsCapabilities(xmlDom);
var i = 0;
// using for loop to add multiple layers to layer manager
// Retrieve a WmsLayerCapabilities object by
// the desired layer name
var wmsLayerCapabilities = wms.getNamedLayer(layerPoint.name);
// Form a configuration object from the
// WmsLayerCapability object
var wmsConfig =
WorldWind.WmsLayer.formLayerConfiguration(wmsLayerCapabilities);
// Modify the configuration objects title property to a
// more user friendly title
wmsConfig.title = wmsLayerCapabilities.title;
var wmsLayer;
wmsLayer = new WorldWind.WmsTimeDimensionedLayer(wmsConfig);
wmsLayer.time = wmsConfig.timeSequences[0].startTime;
// disable layer by default
wmsLayer.enabled = false;
// Add layers to World Wind and update the layer manager
wwd.addLayer(wmsLayer);
//Generate the html
var layerButtonsHTML =
'<button class="btn-info wmsButton" ' +
'id="layerToggle' + layerNumber + '">' +
wmsLayerCapabilities.title + '</button>';
//Append html somehwere
$('#wms').append(layerButtonsHTML);
$('#layerToggle' + layerNumber).button();
generateLayerControl(wwd, wmsConfig, wmsLayerCapabilities,
wmsConfig.title, layerNumber);
//Readd layercontrols
setLayerControls();
layerManager.synchronizeLayerList();
giveWMSTLayersFunctionality(layerNumber, wmsLayer);
return wmsLayer;
};
// Called if an error occurs during WMS Capabilities
// document retrieval
var logError = function(jqXhr, text, exception) {
console.log("There was a failure retrieving the capabilities" +
" document: " + text + " exception: " + exception);
};
$.get(layerPoint.address).done(createWMTSLayer).fail(logError);
}
/**
* This function generates the HTML first then supplies functionality
* Given a layerName and its layernumber, generate a layer control block
*
* @param {WorldWindow} wwd - world window
* @param {Object} wmsConfig - object containing how layer should look
* @param {WmsLayerCapabilities} wmsLayerCapabilities -
* object representing what the wmslayer can do
* @param {String} layerName - name of layer
* @param {Number} layerNumber - number of layer in list
*/
function generateLayerControl(wwd, wmsConfig, wmsLayerCapabilities,
layerName, layerNumber) {
//Generate the div tags
var layerControlHTML = '<div class="toggleLayers" id="funcLayer' +
layerNumber + '">';
layerControlHTML += '<span style="display:none">Layer Controls for ' +
layerName + '</span>';
//Spawn opacity controller
layerControlHTML += generateOpacityControl(layerNumber);
//Spawn the legend
layerControlHTML += generateLegend(wmsLayerCapabilities);
//Spawn the time if it has it
if (typeof(wmsConfig.timeSequences) != 'undefined') {
layerControlHTML += generateTimeControl(layerName,
layerNumber, wmsConfig);
}
layerControlHTML += '</div>';
//Place the HTML somewhere
$("#wms").append(layerControlHTML);
//Add functionality to opacity slider
giveOpacitySliderFunctionality(wwd, layerName, layerNumber);
//Check time again to add functionality
if (typeof(wmsConfig.timeSequences) != 'undefined') {
giveTimeButtonFunctionality(wwd, layerName, layerNumber,
wmsConfig);
}
}
/**
* Creates a legend for a layer given its name and number
*
* @param {Object} wmsLayerCapabilities - object representing what the wms layer
* can do
* @returns {String} contains the HTML to generate
*/
function generateLegend(wmsLayerCapabilities) {
//Check if a legend exists for a given layer this
var legendHTML = '<br><h5><b>Legend</b></h5>';
//Be thorough on checking the existence
if ((wmsLayerCapabilities.styles !=
null) && (wmsLayerCapabilities.styles[0].legendUrls[0]) !=
null) {
//Create the legend tag
var legendURL = wmsLayerCapabilities.styles[0].legendUrls[0].url;
legendHTML += '<div><img src="' + legendURL + '"></div><br><br>';
} else {
//Say it does not exist
legendHTML += '<div><p>A legend does not exist ' +
'for this layer</p></div>';
}
return legendHTML;
}
/**
* Generates opacity control for a layer in HTML
*
* @param {Number} layerNumber - identifier to place layer
* @returns {String} contains the HTML for opacity control
*/
function generateOpacityControl(layerNumber) {
//Create the general box
var opacityHTML = '<br><h5><b>Opacity';
//Create the slider
opacityHTML += '<div id="opacity_slider_' + layerNumber + '"></div>';
//Create the output
opacityHTML += '<div id="opacity_amount_' +
layerNumber + '">100%</div>';
return opacityHTML;
}
/**
* Gives layer opacity control given its name
*
* @param {WorldWindow} wwd - world window
* @param {String} layerName - name of layer to give opacity control
* @param {Number} layerNumber - id of layer
*/
function giveOpacitySliderFunctionality(wwd, layerName, layerNumber) {
//Add functionality to the slider
var sliderStringTemplate = "#opacity_slider_";
var sliderString = sliderStringTemplate.concat(layerNumber);
var slider = $(sliderString);
//Slider details
slider.slider({
value: 1,
min: 0,
max: 1,
step: 0.1
});
var opacity_amount = $("#opacity_amount_" + layerNumber);
//Update values upon slide
slider.on("slide", function(event, ui) {
opacity_amount.html(ui.value * 100 + "%");
});
//Grab the layer and redraw
slider.on("slidestop", function(event, ui) {
//Grabbing the layer is based on its name in addition to
// the entire wwd
for (var i = 0; i < wwd.layers.length; i++) {
var target_layer = wwd.layers[i];
if (target_layer.displayName == layerName) {
//Match, set the opacity
target_layer.opacity = ui.value;
if (document.wwd_duplicate) {
if (!(document.wwd_duplicate instanceof Array))
document.wwd_duplicate.redraw();
else {
document.wwd_duplicate.forEach(
function(element) {
element.redraw();
});
}
}
}
}
});
}
/**
* Generates remove button for graphs
*/
function generateRemoveButton() {
//Generate the remove button for the graphs
var removeHTML = '<p><button class="btn-info" ' +
'id="removeButton">Remove All Graphs</button></p>';
$("#graphs").append(removeHTML);
var removeButton = $('#removeButton');
removeButton.button();
removeButton.on('click', function() {
//Just purge all the children of the almighty graph
var almightyGraphDiv = $('#almightyGraph > div');
var i = 0;
for (i = 0; i < almightyGraphDiv.length; i++) {
$(almightyGraphDiv[i]).html('');
}
});
}
/**
* Generates time HTML control for specified layer
*
* @param {String} layerName - name of layer to give time control
* @param {Number} layerNumber - number id for layer
* @param {Object} wmsConfig - WMS configuration for layer control
* @returns {String} contains the HTML of the time control
*/
function generateTimeControl(layerName, layerNumber, wmsConfig) {
//Create the general box
//Create the output
var startDate;
var endDate;
//modify the string based on whether it is monthly or daily
if (layerName.indexOf("month") != -1) {
//Forcibly remove the month format
startDate =
wmsConfig.timeSequences[0].startTime.toDateString().substring(4, 7) + " " +
wmsConfig.timeSequences[0].startTime.toDateString().substring(11, 15);
endDate = wmsConfig.timeSequences[wmsConfig.timeSequences.length -
1].endTime.toDateString().substring(4, 7) + " " +
wmsConfig.timeSequences[wmsConfig.timeSequences.length -
1].endTime.toDateString().substring(11, 15);
} else {
//Simply output the date time stamp
startDate = wmsConfig.timeSequences[0].startTime.toDateString();
endDate = wmsConfig.timeSequences[wmsConfig.timeSequences.length -
1].endTime.toDateString();
}
//Generate the appropiate html with our dates
var timeHTML = '<h5><b>Time Scale:</b> ' + startDate + ' - ' +
endDate + '</h5>';
timeHTML += '<div id="time_scale_' + layerNumber + '"></div>';
timeHTML += '<div id="time_date_' + layerNumber + '"><br>' +
'Current Time: Use the Time Scale</div>';
//Wrap up the HTML
timeHTML += '</div>';
timeHTML += '<br>';
return timeHTML;
}
/**
* Simply provides functionality to the time control button.
* @param {WorldWindow} wwd - the world window for the globe.
* @param {String} layerName - the name of the layer ro search for
* @param {Number} layerNumber - the div to refer to
* @param {Object} wmsConfig configuration of the layer
*/
//Provides basic functionality for the time slider
function giveTimeButtonFunctionality(wwd, layerName, layerNumber,
wmsConfig) {
var leftButtonTemplate = "#time_left_";
var leftButtonString = leftButtonTemplate.concat(layerNumber);
var rightButtonTemplate = "#time_right_";
var rightButtonString = rightButtonTemplate.concat(layerNumber);
var leftButton = $(leftButtonString);
var rightButton = $(rightButtonString);
leftButton.button();
var targetLayer = getLayerFromName(wwd, layerName);
var slider = $('#time_scale_' + layerNumber).slider();
var length;
//As of now, the time is stored into sequences
//We split the slider up into pieces based on the array length
if (wmsConfig.timeSequences.length > 1) {
length = wmsConfig.timeSequences.length;
} else {
length = 1;
}
//We vary our range based on these values
slider.slider({
value: Math.round(wmsConfig.timeSequences.length / 2),
min: 0,
max: length - 0.01,
step: 0.01
});
//Get the time using inbuilts of time sequences
//(see worldwind documentation)
slider.on('slide', function(event, ui) {
var timeNumber = ui.value - Math.floor(ui.value);
var segmentNumber = Math.floor(ui.value);
$('#time_date_' + layerNumber).html('<br>Current time for this layer: ' +
wmsConfig.timeSequences[segmentNumber].getTimeForScale(timeNumber).toDateString().substring(4));
});
slider.on('slidestop', function(event, ui) {
var timeNumber = ui.value - Math.floor(ui.value);
var segmentNumber = Math.floor(ui.value);
targetLayer.time =
wmsConfig.timeSequences[segmentNumber].getTimeForScale(timeNumber);
});
}
/**
* Searches for a layer given name and returns the layer object
*
* @param {WorldWindow} wwd - world window of the globe
* @param {String} layerName - name of layer to search for
* @returns {Layer} the correct layer object, 0 otherwise
*/
function getLayerFromName(wwd, layerName) {
var i = 0;
for (i = 0; i < wwd.layers.length; i++) {
if (wwd.layers[i].displayName == layerName) {
return wwd.layers[i];
}
}
return 0;
}
/**