-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
3085 lines (2852 loc) · 107 KB
/
index.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 APIKEY = '26fb68df7323284ea4430d8e4d3c60b1';
var geoMode = 0;
requirejs.config({
waitSeconds: 180
});
requirejs({
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"
}
}, ['src/WorldWind',
'./LayerManager', 'src/formats/kml/KmlFile',
'src/formats/kml/controls/KmlTreeVisibility', './Pin', 'jquery',
'jqueryui', 'jquery-csv', 'simple-stats', 'regression', "resizejs"
],
function(ww,
LayerManager, KmlFile, KmlTreeVisibility) {
"use strict";
WorldWind.Logger.setLoggingLevel(WorldWind.Logger.LEVEL_WARNING);
WorldWind.configuration.baseUrl = '';
var regression = require("regression");
var ResizeSensor = require("resizejs");
var wwd = new WorldWind.WorldWindow("canvasOne");
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);
}
// Web Map Service information from NASA's Near Earth Observations WMS
// Named layer displaying Average Temperature data
//Load the WMTS layers
var geoJSONData = loadGEOJsonData();
//Load the country data
var csvData = loadCSVData();
var csvMultiData = loadCSVDataArray();
var agriData = convertArrayToDataSet(csvMultiData[0]);
var atmoData = convertArrayToDataSet(csvMultiData[1]);
var priceData = convertArrayToDataSet(csvMultiData[2]);
var liveData = convertArrayToDataSet(csvMultiData[3]);
var emissionAgriData = convertArrayToDataSet(csvMultiData[4]);
var atmoDataMonthly = convertArrayToDataSet(csvMultiData[5]);
var pestiData = convertArrayToDataSet(csvMultiData[6]);
var fertiData = convertArrayToDataSet(csvMultiData[7]);
var yieldData = convertArrayToDataSet(csvMultiData[8]);
var refugeeData = convertArrayToDataSet(csvMultiData[9]);
var agriDef = csvData[2];
//Generate the placemark layers
generatePlacemarkLayer(wwd, csvData);
//Generate the remove button
generateRemoveButton();
//Generate the button for weather
generateWeatherHTML(csvData[0]);
giveWeatherButtonFunctionality();
// Create a layer manager for controlling layer visibility.
var layerManager = new LayerManager(wwd);
layerManager.synchronizeLayerList();
//Generate regression comparison and the provide functionality
generateGeoComparisonButton(agriData);
giveGeoComparisonFunctionality(agriData, geoJSONData, wwd,
layerManager);
//Automatically zoom into Helsinki, Finland
wwd.goTo(new WorldWind.Position(60.1870, 24.8296, 16e5));
var starFieldLayer = new WorldWind.StarFieldLayer();
var atmosphereLayer = new WorldWind.AtmosphereLayer();
//IMPORTANT: add the starFieldLayer before the atmosphereLayer
wwd.addLayer(starFieldLayer);
wwd.addLayer(atmosphereLayer);
wwd.redrawCallbacks.push(runSunSimulation);
//Generate WMS/WMTS Layers
loadWMTSLayers(wwd, layerManager);
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();
}
}
//Handle a pick (only placemarks shall be)
var highlightedItems = [];
var handlePick = function(x, y) {
// 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 == 'Country') {
var dataPoint =
findDataPoint(csvData[0], placeLat, placeLon);
var details = $("#country");
var detailsHTML = '<h4>Country Details</h4>';
detailsHTML +=
'<p>Country: ' + dataPoint.country + '</p>';
detailsHTML +=
'<p>Country Code: ' + dataPoint.code3 +
'</p>';
detailsHTML += '<button class="btn-info"><a ' +
'href="http://www.fao.org/faostat/en/#data/" ' +
'target="_blank">Download Raw Agriculture ' +
'Data</a></button>';
//Get the agriculture data
detailsHTML += generateCountryButtons();
detailsHTML += '<div id="buttonArea"></div>';
details.html(detailsHTML);
//Give functionality for the buttons generated
giveCountryButtonsFunctionality(agriData, priceData,
liveData, emissionAgriData, pestiData,
fertiData, yieldData, refugeeData, agriDef,
dataPoint.code3);
//fixed hover flags bug - now click instead of
// hover eventlistener
var otherTab = $("#layers");
var otherTab2 = $("#graphs");
var otherTab3 = $("#station");
var otherTab4 = $("#comp");
var otherTab5 = $("#wms");
var otherTab6 = $("#weather");
var otherTab7 = $("#view");
details.show();
otherTab.hide();
otherTab2.hide();
otherTab3.hide();
otherTab4.hide();
otherTab5.hide();
otherTab6.hide();
otherTab7.hide();
$('.glyphicon-globe').css('color', 'white');
$('.fa-map').css('color', 'white');
$('.glyphicon-cloud').css('color', 'white');
$('.fa-area-chart').css('color', 'white');
$('.glyphicon-briefcase').css('color', 'white');
$('.fa-sun-o').css('color', 'white');
$('.glyphicon-eye-open').css('color', 'white');
$('.glyphicon-flag').css('color', 'lightgreen');
$('.resizable').show();
} else if (pickList.objects[i].userObject.type ==
'Weather Station') {
var atmoDataPoint =
findDataPoint(csvData[1], placeLat, placeLon);
var countryData = csvData[0];
var ccode2 = atmoDataPoint.stationName.slice(0, 2);
var ccode3 = findDataPointCountry(countryData,
ccode2, 2).code3;
var agriDataPoint = findDataPointCountry(agriData, ccode3, 3);
var details = $('#station');
var detailsHTML = '<h4>Weather Station Detail</h4>';
detailsHTML += '<p>Station Name: ' +
atmoDataPoint.stationName + '</p>';
detailsHTML += '<button class="btn-info">' +
'<a href="https://fluxnet.fluxdata.org//' +
'data/download-data/" ' +
'target="_blank">Download Raw Atmosphere' +
' Data (Fluxnet Account Required)</a></button>'
//Generate the station buttons
detailsHTML += generateAtmoButtons(atmoData,
atmoDataMonthly, atmoDataPoint.stationName);
details.html(detailsHTML);
//Generate the plots
//Give functionality for buttons generated
giveAtmoButtonsFunctionality(atmoData,
atmoDataMonthly, refugeeData,
atmoDataPoint.stationName,
ccode3,
agriDataPoint);
var otherTab = $("#layers");
var otherTab2 = $("#graphs");
var otherTab3 = $("#country");
var otherTab4 = $("#comp");
var otherTab5 = $("#wms");
var otherTab6 = $("#weather");
var otherTab7 = $("#view");
details.show();
$('.resizable').show();
otherTab.hide();
otherTab2.hide();
otherTab3.hide();
otherTab4.hide();
otherTab5.hide();
otherTab6.hide();
otherTab7.hide();
$('.glyphicon-globe').css('color', 'white');
$('.fa-map').css('color', 'white');
$('.glyphicon-cloud').css('color', 'lightgreen');
$('.fa-area-chart').css('color', 'white');
$('.glyphicon-briefcase').css('color', 'white');
$('.fa-sun-o').css('color', 'white');
$('.glyphicon-eye-open').css('color', 'white');
$('.glyphicon-flag').css('color', 'white');
}
}
}
}
};
// 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);
// Listen for mouse clicks.
var clickRecognizer = new WorldWind.ClickRecognizer(wwd, handleClick);
// Listen for taps on mobile devices.
var tapRecognizer = new WorldWind.TapRecognizer(wwd, handleClick);
/**
* This function generates the HTML first then supplies functionality
*Given a layerName and its layernumber, generate a layer control block
*
* @param wwd - world window
* @param wmsConfig - object containing how layer should look
* @param wmsLayerCapabilities - object representing what the wms
* layer can do
* @param layerName - name of layer
* @param 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);
}
}
/**
* Searches for a layer given name and returns the layer object
*
* @param wwd - world window
* @param layerName - name of layer to search for
* @returns the correct layer object
*/
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;
}
/**
* creates a legend for a layer given its name and number
*
* @param wwd - worldwindow
* @param wmsLayerCapabilities - object representing what the wms layer
* can do
* @param layerName - name of layer
* @param layerNumber - where it should be generated among other layers
* @returns {string containing HTML code to create a legend}
*/
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 layerNumber - identifier to place layer
* @returns {string containing HTML to create opacity slider for layer}
*/
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 wwd - world window
* @param layerName - name of layer to give opacity control
* @param 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 time HTML control for specified layer
*
* @param layerName - name of layer to give time control
* @param layerNumber - number id for layer
* @param wmsConfig - WMS configuration for layer control
* @returns {string containing HTML code for 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;
}
//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);
});
}
//loading screen
setTimeout(function() {
$("#loading_modal").fadeOut();
}, 3000);
$(document).ready(function() {
$('#sidebarCollapse').on('click', function() {
$('#sidebar').toggleClass('active');
$(this).toggleClass('active');
});
});
//Generates the placemark layers
//The types are predetermined in order
//This assumes the CSV data is loaded in order too obviously
//Assumption is dataType 1 maps to csvData 1
function generatePlacemarkLayer(wwd, csvData) {
//Data type list
var dataTypes = ['Country', 'Weather Station'];
//Common features
var pinLibrary = WorldWind.configuration.baseUrl +
"images/pushpins/",
placemarkAttributes = new WorldWind.PlacemarkAttributes(null),
highlightAttributes;
placemarkAttributes.imageScale = 1;
placemarkAttributes.imageOffset = new WorldWind.Offset(
WorldWind.OFFSET_FRACTION, 0.3,
WorldWind.OFFSET_FRACTION, 0.0);
placemarkAttributes.imageColor = WorldWind.Color.WHITE;
placemarkAttributes.labelAttributes.offset = new WorldWind.Offset(
WorldWind.OFFSET_FRACTION, 0.5,
WorldWind.OFFSET_FRACTION, 1.0);
placemarkAttributes.labelAttributes.color = WorldWind.Color.WHITE;
placemarkAttributes.drawLeaderLine = true;
placemarkAttributes.leaderLineAttributes.outlineColor =
WorldWind.Color.RED;
// Define the images we'll use for the placemarks.
var images = [
"plain-black.png", "plain-blue.png", "plain-brown.png",
"plain-gray.png", "plain-green.png", "plain-orange.png",
"plain-purple.png", "plain-red.png", "plain-teal.png",
"plain-white.png", "plain-yellow.png", "castshadow-black.png",
"castshadow-blue.png", "castshadow-brown.png",
"castshadow-gray.png",
"castshadow-green.png", "castshadow-orange.png",
"castshadow-purple.png", "castshadow-red.png",
"castshadow-teal.png", "castshadow-white.png"
];
var i = 0;
for (i = 0; i < dataTypes.length; i++) {
var placemarkLayer = new WorldWind.RenderableLayer(dataTypes[i] +
" Placemarks");
//Create the pins
var j = 0;
for (j = 0; j < csvData[i].length; j++) {
// Create the placemark and its label.
var placemark = new WorldWind.Placemark(new WorldWind.Position(parseFloat(csvData[i][j].lat),
parseFloat(csvData[i][j].lon), 1e2), true, null);
var labelString = '';
//Handle the string is based on the type we determine
if (dataTypes[i] == 'Country') {
labelString = csvData[i][j].country + ' - ' +
csvData[i][j].code3;
} else if (dataTypes[i] == 'Weather Station') {
labelString = csvData[i][j].code3;
}
placemark.label = labelString;
placemark.altitudeMode = WorldWind.RELATIVE_TO_GROUND;
// Create the placemark attributes for this placemark.
//the attributes differ only by their image URL.
placemarkAttributes = new
WorldWind.PlacemarkAttributes(placemarkAttributes);
placemarkAttributes.imageSource =
pinLibrary + images[9 - 2 * i];
//Use flag if it is a country
if (dataTypes[i] == 'Country') {
//Image would be a flag
placemarkAttributes.imageSource = './flags/' +
csvData[i][j].iconCode + '.png';
placemark.userObject = {
code3: csvData[i][j].code3,
country: csvData[i][j].country
};
} else if (dataTypes[i] == 'Weather Station') {
placemarkAttributes.imageSource =
'images/sun.png';
}
placemark.attributes = placemarkAttributes;
// Create the highlight attributes for this placemark.
//Note that the normal attributes are specified as
// the default highlight attributes so all properties are
//identical except the image scale. You could
// vary the color, image, or other property to control
//the highlight representation.
highlightAttributes = new
WorldWind.PlacemarkAttributes(placemarkAttributes);
highlightAttributes.imageScale = 3;
placemark.highlightAttributes = highlightAttributes;
//Attach the type to it
placemark.type = dataTypes[i];
//Make it so the labels are visible from 10e6
placemark.eyeDistanceScalingLabelThreshold = 10e6;
placemark.eyeDistanceScalingThreshold = 5e6;
// Add the placemark to the layer.
placemarkLayer.addRenderable(placemark);
}
//Before adding to the layer, attach a type to it
placemarkLayer.type = dataTypes[i];
// Add the placemarks layer to the World Window's layer list.
wwd.addLayer(placemarkLayer);
}
}
/**
* Loads all CSV Files
* @returns {Array of CSV data}
*/
function loadCSVData() {
var csvList = ['csvdata/countries.csv',
'csvdata/weatherstations.csv', 'csvdata/cropAcros.csv'
];
//Find the file
var csvString = "";
var csvData = [];
var i = 0;
for (i = 0; i < csvList.length; i++) {
var csvRequest = $.ajax({
async: false,
url: csvList[i],
success: function(file_content) {
csvString = file_content;
csvData.push($.csv.toObjects(csvString));
}
});
}
return csvData;
}
/**
* Get data given latitude and longitude of a location
*
* @param dataSet - data to get from location
* @param lat - latitude value of location
* @param lon - longitude value of location
* @returns {Data for specified location}
*/
function findDataPoint(dataSet, lat, lon) {
var i = 0;
for (i = 0; i < dataSet.length; i++) {
if ((dataSet[i].lon == lon) && (dataSet[i].lat == lat)) {
return dataSet[i];
}
}
}
/**
* Find data given name of station
*
* @param dataSet - type of data to get for
* @param stationName - name of station to get data for
* @returns {data for specified station}
*/
function findDataPointStation(dataSet, stationName) {
var i = 0;
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].code3 == stationName) {
return dataSet[i];
}
}
return 0;
}
/**
* Get definition of crop given name
* @param dataSet - data from which to search
* @param cropName - name of crop to get definition for
* @returns {definition and statement of crop from FAO}
*/
function findCropDefinition(dataSet, cropName) {
var i = 0;
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].Item == cropName) {
return dataSet[i].Description;
}
}
return 0;
}
/**
* find all data for a country given its code
*
* @param dataSet - all the data to get
* @param countryCode - country's 2 or 3 letter code
* @param codeNumber - number of code
* @returns {*}
*/
function findDataPointCountry(dataSet, countryCode, codeNumber) {
var i = 0;
if (codeNumber == 2) {
for (i = 0; i < dataSet.length; i++) {
if ((dataSet[i].code2 == countryCode)) {
return dataSet[i];
}
}
} else if (codeNumber == 3) {
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].code3 == countryCode) {
return dataSet[i];
}
}
}
return 0;
}
/**
* Loads CSV file in a different format (for FAO data)
* @returns {Array of data sets from FAO}
*/
function loadCSVDataArray() {
var csvList = ['csvdata/FAOcrops.csv', 'csvdata/Atmo.csv',
'csvdata/prices2.csv', 'csvdata/livestock.csv',
'csvdata/emissionAll.csv', 'csvdata/Monthly_AvgData1.csv',
'csvdata/pesti.csv', 'csvdata/ferti.csv',
'csvdata/yield.csv', 'csvdata/refugeeout.csv'
];
//Find the file
var csvString = "";
var csvData = [];
var i = 0;
//Send out request and grab the csv file content
for (i = 0; i < csvList.length; i++) {
var csvRequest = $.ajax({
async: false,
url: csvList[i],
success: function(file_content) {
csvString = file_content;
csvData.push($.csv.toArrays(csvString));
}
});
}
return csvData;
}
function loadFile(fileName) {
var output;
var request = $.ajax({
async: false,
url: fileName,
success: function(file_content) {
output = $.csv.toArrays(file_content);
}
})
return output;
}
//Find a value given a name
//Returns 0 if it can't be found, else returns something
//This assumes we are working with convertArrayToDataSet
function findDataBaseName(inputArray, name) {
var i = 0;
for (i = 0; i < inputArray.length; i++) {
//Find if the name exists
if (inputArray[i].code3 == name) {
return inputArray[i];
}
}
return 0;
}
/**
* Given a csv data array, convert the segment into objects
*
* @param csvData - in the format of id, paramatertype, year1 value,
* year2 value...
* @returns {Array of objects containing the ids and an array of year-
* value pairs}
*/
function convertArrayToDataSet(csvData) {
//Create the temporary object
var objectList = [];
var i = 0;
for (i = 1; i < csvData.length; i++) {
//Create the object
var tempObject = {};
var needPushToObj;
//First instance or can't find it
if ((objectList.length == 0) ||
(findDataBaseName(objectList, csvData[i][0]) == 0)) {
//Give it a name assuming it is the first things
tempObject.code3 = csvData[i][0]
//Give it a start time
tempObject.startTime = csvData[0][2];
tempObject.endTime = csvData[0][csvData[i].length - 1];
//Give it a data array
tempObject.dataValues = [];
needPushToObj = true;
} else {
//We found it
tempObject = findDataBaseName(objectList, csvData[i][0]);
needPushToObj = false;
}
var j = 0;
//Data values contain a type and its year
var dataValueObject = {};
dataValueObject.timeValues = [];
for (j = 1; j < csvData[i].length; j++) {
//Attach things to the tempObject dataValues
if (j == 1) {
//Its the type name
dataValueObject.typeName = csvData[i][1];
} else {
//Append the item to the value
var timeValue = {};
timeValue.year = csvData[0][j];
//Check if the data exist
var value = csvData[i][j];
if (value != "") {
//Parse it
timeValue.value = parseFloat(value);
} else {
timeValue.value = "";
}
dataValueObject.timeValues.push(timeValue);
}
}
tempObject.dataValues.push(dataValueObject);
//Check to push to obj list
if (needPushToObj) {
objectList.push(tempObject);
}
}
return objectList;
}
/**
* preloads WMTS layers
*
* @param wwd - worldwindow
* @param layerManager - layerManager from layerManager.js
*/
function loadWMTSLayers(wwd, layerManager) {
var serviceWMTSAddress = "https://neowms.sci.gsfc.nasa.gov/wms/wms";
var layerName = ["TRMM_3B43M", "MYD28M", "MOD11C1_D_LSTDA",
"MOD11C1_D_LSTNI", "MOD_143D_RR"
];
var totalLayers = [];
// 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
for (i = 0; i < layerName.length; i++) {
// Retrieve a WmsLayerCapabilities object by
// the desired layer name
var wmsLayerCapabilities = wms.getNamedLayer(layerName[i]);
// 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;
totalLayers.push(wmsLayer);
// 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' + i + '">' +
wmsLayerCapabilities.title + '</button>';
//Append html somehwere