-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathMap_.js
More file actions
1849 lines (1691 loc) · 68 KB
/
Map_.js
File metadata and controls
1849 lines (1691 loc) · 68 KB
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
import $ from 'jquery'
import * as d3 from 'd3'
import F_ from '../Formulae_/Formulae_'
import L_ from '../Layers_/Layers_'
import { captureVector } from '../Layers_/LayerCapturer'
import {
constructVectorLayer,
constructSublayers,
} from '../Layers_/LayerConstructors'
import Filtering from '../Layers_/Filtering/Filtering'
import Viewer_ from '../Viewer_/Viewer_'
import Globe_ from '../Globe_/Globe_'
import ToolController_ from '../ToolController_/ToolController_'
import CursorInfo from '../../Ancillary/CursorInfo'
import Description from '../../Ancillary/Description'
import QueryURL from '../../Ancillary/QueryURL'
import MetadataCapturer from '../Layers_/MetadataCapturer.js'
import { Kinds } from '../../../pre/tools'
import DataShaders from '../../Ancillary/DataShaders'
import calls from '../../../pre/calls'
import TimeControl from '../../Ancillary/TimeControl'
import gjv from 'geojson-validation'
import {
evaluate_cmap,
data as colormapData,
} from '../../../external/js-colormaps/js-colormaps.js'
let L = window.L
let essenceFina = function () {}
import GeoRasterLayer from '../../../external/georaster-layer-for-leaflet/georaster-layer-for-leaflet.ts'
import georaster from 'georaster'
// The default color ramp used for image layer types
const IMAGE_DEFAULT_COLOR_RAMP = 'binary'
let Map_ = {
//Our main leaflet map variable
map: null,
toolbar: null,
tempOverlayImage: null,
activeLayer: null,
allLayersLoadedPassed: false,
player: { arrow: null, lookat: null },
//Initialize a map based on a config file
init: function (essenceFinal) {
essenceFina = essenceFinal
//Repair Leaflet and plugin incongruities
L.DomEvent._fakeStop = L.DomEvent.fakeStop
//var fakeStop = L.DomEvent.fakeStop || L.DomEvent._fakeStop || stop;?
/*
var xhr = new XMLHttpRequest();
try {
xhr.open("GET", 'Missions/MTTT/Layers/TEMP/M2020_EDL_bufpoints_3m_geo/12/2929/1834.pbf');
xhr.responseType = "arraybuffer";
xhr.onerror = function() {
console.log("Network error")
};
xhr.onload = function() {
if (xhr.status === 200) {
var data = new Pbf(new Uint8Array(xhr.response)).readFields(readData, {});
console.log( data )
function readData(tag, data, pbf) {
if (tag === 1) data.name = pbf.readString();
else if (tag === 2) data.version = pbf.readVarint();
//else if (tag === 3) data.layer = pbf.readMessage(readLayer, {});
}
function readLayer(tag, layer, pbf) {
if (tag === 1) layer.name = pbf.readString();
else if (tag === 3) layer.size = pbf.readVarint();
}
}
else console.log(xhr.statusText);
};
xhr.send();
} catch (err) {
console.log(err.message)
}
*/
var hasZoomControl = false
if (L_.configData.look && L_.configData.look.zoomcontrol)
hasZoomControl = true
Map_.mapScaleZoom = L_.configData.msv.mapscale || null
if (this.map != null) this.map.remove()
let shouldFade = true
if (
L_.configData.projection &&
L_.configData.projection.custom === true
) {
var cp = L_.configData.projection
//console.log(cp)
var crs = new L.Proj.CRS(
Number.isFinite(parseInt(cp.epsg[0]))
? `EPSG:${cp.epsg}`
: cp.epsg,
cp.proj,
{
origin: [
parseFloat(cp.origin[0]),
parseFloat(cp.origin[1]),
],
resolutions: cp.res,
bounds: L.bounds(
[parseFloat(cp.bounds[0]), parseFloat(cp.bounds[1])],
[parseFloat(cp.bounds[2]), parseFloat(cp.bounds[3])]
),
},
parseFloat(L_.configData.msv.radius.major)
)
crs.projString = cp.proj
this.map = L.map('map', {
zoomControl: hasZoomControl,
editable: true,
keyboard: false,
crs: crs,
zoomDelta: 0.05,
zoomSnap: 0,
fadeAnimation: shouldFade,
//wheelPxPerZoomLevel: 500,
})
window.mmgisglobal.customCRS = crs
} else {
//Make the empty map and turn off zoom controls
this.map = L.map('map', {
zoomControl: hasZoomControl,
editable: true,
keyboard: false,
fadeAnimation: shouldFade,
//crs: crs,
//zoomDelta: 0.05,
//zoomSnap: 0,
//wheelPxPerZoomLevel: 500,
})
// Default CRS
const projString = `+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=${F_.radiusOfPlanetMajor} +b=${F_.radiusOfPlanetMinor} +towgs84=0,0,0,0,0,0,0 +units=m +no_defs`
window.mmgisglobal.customCRS = new L.Proj.CRS(
'EPSG:3857',
projString,
null,
F_.radiusOfPlanetMajor
)
window.mmgisglobal.customCRS.projString = projString
}
if (this.map.zoomControl) this.map.zoomControl.setPosition('topright')
if (Map_.mapScaleZoom) {
L.control
.scalefactor({
radius: parseInt(L_.configData.msv.radius.major),
mapScaleZoom: Map_.mapScaleZoom,
})
.addTo(this.map)
}
//Initialize the view to that set in config
if (L_.FUTURES.mapView != null) {
this.resetView(L_.FUTURES.mapView)
if (L_.FUTURES.centerPin != null) {
this._centerPin = new L.circleMarker(
[L_.FUTURES.mapView[0], L_.FUTURES.mapView[1]],
{
fillColor: '#000',
fillOpacity: 0,
color: 'lime',
weight: 2,
}
)
.setRadius(4)
.addTo(this.map)
if (
L_.FUTURES.centerPin.length > 0 &&
L_.FUTURES.centerPin != 'true'
) {
this._centerPin.on('mouseover', function () {
CursorInfo.update(L_.FUTURES.centerPin, null, false)
})
this._centerPin.on('mouseout', function () {
CursorInfo.hide()
})
}
}
} else {
this.resetView(L_.view)
}
//Remove attribution
d3.select('.leaflet-control-attribution').remove()
//Make our layers
makeLayers(L_.layers.dataFlat)
//Just in case we have no layers
allLayersLoaded()
//Add a graticule
if (L_.configData.look && L_.configData.look.graticule == true) {
this.toggleGraticule(true)
}
//When done zooming, hide the things you're too far out to see/reveal the things you're close enough to see
this.map.on('zoomend', function () {
L_.enforceVisibilityCutoffs()
// Set all zoom elements
$('.map-autoset-zoom').text(Map_.map.getZoom())
})
this.map.on('movestart', fadeOutCertainLayers)
this.map.on('zoomstart', fadeOutCertainLayers)
function fadeOutCertainLayers() {
// Fade out Velocity layer Streamlines to prevent rendering jumps
Object.keys(L_.layers.data).forEach((layerUUID) => {
const layerData = L_.layers.data[layerUUID]
if (
layerData.type === 'velocity' &&
(layerData.kind === 'streamlines' || layerData.kind == null)
) {
L_.layers.layer[layerUUID].setOpacity(0)
}
})
}
if (Globe_.controls.link) {
this.map.on('move', (e) => {
const c = this.map.getCenter()
Globe_.controls.link.linkMove(c.lng, c.lat)
})
this.map.on('mousemove', (e) => {
Globe_.controls.link.linkMouseMove(e.latlng.lng, e.latlng.lat)
})
this.map.on('mouseout', (e) => {
Globe_.controls.link.linkMouseOut()
})
}
// Clear the selected feature if clicking on the map where there are no features
Map_.map.addEventListener('click', clearOnMapClick)
//Build the toolbar
buildToolBar()
//Set the time for any time enabled layers
TimeControl.updateLayersTime()
},
toggleGraticule: function (on) {
if (on)
this.graticule = L.latlngGraticule({
showLabel: true,
color: 'rgba(255,255,255,0.75)',
weight: 1,
zoomInterval: [
{ start: 2, end: 3, interval: 40 },
{ start: 4, end: 5, interval: 20 },
{ start: 6, end: 7, interval: 10 },
{ start: 8, end: 9, interval: 5 },
{ start: 10, end: 11, interval: 0.4 },
{ start: 12, end: 13, interval: 0.2 },
{ start: 14, end: 15, interval: 0.1 },
{ start: 16, end: 17, interval: 0.01 },
{ start: 18, end: 19, interval: 0.005 },
{ start: 20, end: 21, interval: 0.0025 },
{ start: 21, end: 30, interval: 0.00125 },
],
}).addTo(Map_.map)
else {
this.rmNotNull(this.graticule)
this.graticule = null
}
},
clear: function () {
this.map.eachLayer(function (layer) {
Map_.map.removeLayer(layer)
})
this.toolbar = null
this.tempOverlayImage = null
this.activeLayer = null
this.allLayersLoadedPassed = false
this.player = { arrow: null, lookat: null }
},
setZoomToMapScale() {
this.map.setZoom(this.mapScaleZoom)
},
//Focuses the map on [lat, lon, zoom]
resetView: function (latlonzoom, stopNextMove) {
//Uses Leaflet's setView
var lat = parseFloat(latlonzoom[0])
if (isNaN(lat)) lat = 0
var lon = parseFloat(latlonzoom[1])
if (isNaN(lon)) lon = 0
var zoom = parseInt(latlonzoom[2])
if (zoom == null || isNaN(zoom))
zoom =
this.map.getZoom() ||
L_.configData.msv.mapscale ||
L_.configData.msv.view[2]
this.map.setView([lat, lon], zoom)
this.map.invalidateSize()
},
//returns true if the map has the layer
hasLayer: function (layername) {
if (L_.layers.layer[layername]) {
return Map_.map.hasLayer(L_.layers.layer[layername])
}
return false
},
//adds a temp tile layer to the map
tempTileLayer: null,
changeTempTileLayer: function (url) {
this.removeTempTileLayer()
this.tempTileLayer = L.tileLayer(url, {
minZoom: 0,
maxZoom: 25,
maxNativeZoom: 25,
tms: true, //!!!
noWrap: true,
continuousWorld: true,
reuseTiles: true,
}).addTo(this.map)
},
//removes that layer
removeTempTileLayer: function () {
this.rmNotNull(this.tempTileLayer)
},
//Removes the map layer if it isn't null
rmNotNull: function (layer) {
if (layer != null) {
this.map.removeLayer(layer)
layer = null
}
},
//Redraws all layers, starting with the bottom one
orderedBringToFront: function () {
let hasIndex = []
let hasIndexRaster = []
for (let i = L_._layersOrdered.length - 1; i >= 0; i--) {
if (Map_.hasLayer(L_._layersOrdered[i])) {
if (L_.layers.data[L_._layersOrdered[i]]) {
if (
L_.layers.data[L_._layersOrdered[i]].type === 'vector'
) {
if (L_.layers.attachments[L_._layersOrdered[i]]) {
for (let s in L_.layers.attachments[
L_._layersOrdered[i]
]) {
Map_.rmNotNull(
L_.layers.attachments[L_._layersOrdered[i]][
s
].layer
)
}
}
Map_.map.removeLayer(
L_.layers.layer[L_._layersOrdered[i]]
)
hasIndex.push(i)
} else if (
L_.layers.data[L_._layersOrdered[i]].type === 'tile' ||
L_.layers.data[L_._layersOrdered[i]].type === 'data'
) {
hasIndexRaster.push(i)
} else if (
L_.layers.data[L_._layersOrdered[i]].type === 'image'
) {
Map_.map.removeLayer(
L_.layers.layer[L_._layersOrdered[i]]
)
hasIndex.push(i)
}
}
}
}
// First only vectors and images
for (let i = 0; i < hasIndex.length; i++) {
if (L_.layers.attachments[L_._layersOrdered[hasIndex[i]]]) {
for (let s in L_.layers.attachments[
L_._layersOrdered[hasIndex[i]]
]) {
if (
L_.layers.attachments[L_._layersOrdered[hasIndex[i]]][s]
.on
) {
if (
L_.layers.attachments[
L_._layersOrdered[hasIndex[i]]
][s].type !== 'model'
) {
Map_.map.addLayer(
L_.layers.attachments[
L_._layersOrdered[hasIndex[i]]
][s].layer
)
}
}
}
}
Map_.map.addLayer(L_.layers.layer[L_._layersOrdered[hasIndex[i]]])
// If image layer, reorder the z index and redraw the layer
if (
L_.layers.data[L_._layersOrdered[hasIndex[i]]].type === 'image'
) {
L_.layers.layer[L_._layersOrdered[hasIndex[i]]].setZIndex(
L_._layersOrdered.length +
1 -
L_._layersOrdered.indexOf(
L_._layersOrdered[hasIndex[i]]
)
)
L_.layers.layer[L_._layersOrdered[hasIndex[i]]].clearCache()
L_.layers.layer[L_._layersOrdered[hasIndex[i]]].redraw()
}
}
L_.enforceVisibilityCutoffs()
// Now only rasters
// They're separate because its better to only change the raster z-index
for (let i = 0; i < hasIndexRaster.length; i++) {
L_.layers.layer[L_._layersOrdered[hasIndexRaster[i]]].setZIndex(
L_._layersOrdered.length +
1 -
L_._layersOrdered.indexOf(
L_._layersOrdered[hasIndexRaster[i]]
)
)
}
// Now bring any Drawn layers back to the front:
Object.keys(L_.layers.layer).forEach((key) => {
if (
key.startsWith('DrawTool_') &&
Array.isArray(L_.layers.layer[key])
) {
L_.layers.layer[key].forEach((l) => {
try {
l.bringToFront()
} catch (err) {}
})
}
})
},
refreshLayer: async function (layerObj, cb, skipOrderedBringToFront) {
// If it's a dynamic extent layer, just re-call its function
if (
L_._onSpecificLayerToggleSubscriptions[
`dynamicextent_${layerObj.name}`
] != null
) {
if (L_.layers.on[layerObj.name])
L_._onSpecificLayerToggleSubscriptions[
`dynamicextent_${layerObj.name}`
].func(layerObj.name)
if (typeof cb === 'function') cb()
return true
}
// We need to find and remove all points on the map that belong to the layer
// Not sure if there is a cleaner way of doing this
for (var i = L_._layersOrdered.length - 1; i >= 0; i--) {
if (
L_.layers.data[L_._layersOrdered[i]] &&
L_.layers.data[L_._layersOrdered[i]].type == 'vector' &&
L_.layers.data[L_._layersOrdered[i]].name == layerObj.name
) {
if (L_._layersBeingMade[layerObj.name] !== true) {
const wasOn = L_.layers.on[layerObj.name]
if (wasOn)
L_.toggleLayer(
L_.layers.data[layerObj.name],
skipOrderedBringToFront
) // turn off if on
// fake on
L_.layers.on[layerObj.name] = true
await makeLayer(layerObj, true, null)
L_.addVisible(Map_, [layerObj.name])
// turn off if was off
if (wasOn) L_.layers.on[layerObj.name] = false
L_.toggleLayer(
L_.layers.data[layerObj.name],
skipOrderedBringToFront
) // turn back on/off
L_.enforceVisibilityCutoffs()
} else {
console.error(
`ERROR - refreshLayer: Cannot make layer ${layerObj.display_name}/${layerObj.name} as it's already being made!`
)
if (typeof cb === 'function') cb()
return false
}
if (typeof cb === 'function') cb()
return true
}
}
},
setPlayerArrow(lng, lat, rot) {
var playerMapArrowOffsets = [
[0.06, 0],
[-0.04, 0.04],
[-0.02, 0],
[-0.04, -0.04],
]
var playerMapArrowPolygon = []
if (Map_.map.hasLayer(Map_.player.arrow))
Map_.map.removeLayer(Map_.player.arrow)
var scalar = 512 / Math.pow(2, Map_.map.getZoom())
var rotatedOffsets
for (var i = 0; i < playerMapArrowOffsets.length; i++) {
rotatedOffsets = F_.rotatePoint(
{
x: playerMapArrowOffsets[i][0],
y: playerMapArrowOffsets[i][1],
},
[0, 0],
-rot
)
playerMapArrowPolygon.push([
lat + scalar * rotatedOffsets.x,
lng + scalar * rotatedOffsets.y,
])
}
Map_.player.arrow = L.polygon(playerMapArrowPolygon, {
color: 'lime',
opacity: 1,
lineJoin: 'miter',
weight: 2,
}).addTo(Map_.map)
},
setPlayerLookat(lng, lat) {
if (Map_.map.hasLayer(Map_.player.lookat))
Map_.map.removeLayer(Map_.player.lookat)
if (lat && lng) {
Map_.player.lookat = new L.circleMarker([lat, lng], {
fillColor: 'lime',
fillOpacity: 0.75,
color: 'lime',
opacity: 1,
weight: 2,
})
.setRadius(5)
.addTo(Map_.map)
}
},
hidePlayer(hideArrow, hideLookat) {
if (hideArrow !== false && Map_.map.hasLayer(Map_.player.arrow))
Map_.map.removeLayer(Map_.player.arrow)
if (hideLookat !== false && Map_.map.hasLayer(Map_.player.lookat))
Map_.map.removeLayer(Map_.player.lookat)
},
getScreenDiagonalInMeters() {
let bb = document.getElementById('map').getBoundingClientRect()
let nwLatLng = Map_.map.containerPointToLatLng([0, 0])
let seLatLng = Map_.map.containerPointToLatLng([bb.width, bb.height])
return F_.lngLatDistBetween(
nwLatLng.lng,
nwLatLng.lat,
seLatLng.lng,
seLatLng.lat
)
},
getCurrentTileXYZs() {
const bounds = Map_.map.getBounds()
const zoom = Map_.map.getZoom()
const min = Map_.map
.project(bounds.getNorthWest(), zoom)
.divideBy(256)
.floor(),
max = Map_.map
.project(bounds.getSouthEast(), zoom)
.divideBy(256)
.floor(),
xyzs = [],
mod = Math.pow(2, zoom)
for (var i = min.x; i <= max.x; i++) {
for (var j = min.y; j <= max.y; j++) {
var x = ((i % mod) + mod) % mod
var y = ((j % mod) + mod) % mod
var coords = new L.Point(x, y)
coords.z = zoom
xyzs.push(coords)
}
}
return xyzs
},
makeLayer: makeLayer,
makeLayers: makeLayers,
allLayersLoaded: allLayersLoaded,
}
//Takes an array of layer objects and makes them map layers
function makeLayers(layersObj) {
//Make each layer (backwards to maintain draw order)
for (var i = layersObj.length - 1; i >= 0; i--) {
makeLayer(layersObj[i])
}
}
//Takes the layer object and makes it a map layer
async function makeLayer(
layerObj,
evenIfOff,
forceGeoJSON,
id,
forceMake,
stopLoops
) {
return new Promise(async (resolve, reject) => {
const layerName = L_.asLayerUUID(layerObj.name)
if (forceMake !== true && L_._layersBeingMade[layerName] === true) {
console.error(
`ERROR - makeLayer: Cannot make layer ${layerObj.display_name}/${layerObj.name} as it's already being made!`
)
resolve(false)
return
} else {
L_._layersBeingMade[layerName] = true
}
//Decide what kind of layer it is
//Headers do not need to be made
if (layerObj.type != 'header') {
//Simply call the appropriate function for each layer type
switch (layerObj.type) {
case 'vector':
await makeVectorLayer(
layerObj,
evenIfOff,
null,
forceGeoJSON
)
break
case 'velocity':
await makeVelocityLayer(
layerObj,
evenIfOff,
null,
forceGeoJSON
)
break
case 'tile':
makeTileLayer(layerObj)
break
case 'vectortile':
makeVectorTileLayer(layerObj)
break
case 'query':
await makeVectorLayer(layerObj, false, true, forceGeoJSON)
break
case 'data':
makeDataLayer(layerObj)
break
case 'image':
makeImageLayer(layerObj)
break
case 'model':
//Globe only
makeModelLayer(layerObj)
break
default:
console.warn('Unknown layer type: ' + layerObj.type)
}
}
// release hold on layer
L_._layersBeingMade[layerName] = false
if (stopLoops !== true && layerObj.type === 'vector') {
Filtering.updateGeoJSON(layerObj.name)
Filtering.triggerFilter(layerObj.name)
}
resolve(true)
})
}
//Default is onclick show full properties and onhover show 1st property
Map_.onEachFeatureDefault = onEachFeatureDefault
function onEachFeatureDefault(feature, layer) {
const pv = L_.getLayersChosenNamePropVal(feature, layer)
layer['useKeyAsName'] = Object.keys(pv)[0]
if (
layer.hasOwnProperty('options') &&
layer.options.hasOwnProperty('layerName')
) {
L_.layers.data[layer.options.layerName].useKeyAsName =
layer['useKeyAsName']
}
if (typeof layer['useKeyAsName'] === 'string') {
//Add a mouseover event to the layer
layer.on('mouseover', function () {
//Make it turn on CursorInfo and show name and value
CursorInfo.update(pv, null, false)
})
//Add a mouseout event
layer.on('mouseout', function () {
//Make it turn off CursorInfo
CursorInfo.hide()
})
}
if (
!(
feature.style &&
feature.style.hasOwnProperty('noclick') &&
feature.style.noclick
)
) {
//Add a click event to send the data to the info tab
layer.on('click', (e) => {
featureDefaultClick(feature, layer, e)
})
}
}
Map_.featureDefaultClick = featureDefaultClick
function featureDefaultClick(feature, layer, e) {
if (
ToolController_.activeTool &&
ToolController_.activeTool.disableLayerInteractions === true
)
return
MetadataCapturer.populateMetadata(layer, () => {
Kinds.use(
L_.layers.data[layer.options.layerName].kind,
Map_,
feature,
layer,
layer.options.layerName,
null,
e
)
//update url
if (layer != null && layer.hasOwnProperty('options')) {
var keyAsName
if (layer.hasOwnProperty('useKeyAsName')) {
keyAsName = layer.feature.properties[layer.useKeyAsName]
} else {
keyAsName = layer.feature.properties[0]
}
}
Viewer_.changeImages(feature, layer)
//figure out how to construct searchStr in URL. For example: a ChemCam target can sometime
//be searched by "target sol", or it can be searched by "sol target" depending on config file.
var searchToolVars = L_.getToolVars('search')
var searchfields = {}
if (searchToolVars.hasOwnProperty('searchfields')) {
for (var layerfield in searchToolVars.searchfields) {
var fieldString = searchToolVars.searchfields[layerfield]
fieldString = fieldString.split(')')
for (var i = 0; i < fieldString.length; i++) {
fieldString[i] = fieldString[i].split('(')
var li = fieldString[i][0].lastIndexOf(' ')
if (li != -1) {
fieldString[i][0] = fieldString[i][0].substring(li + 1)
}
}
fieldString.pop()
//0 is function, 1 is parameter
searchfields[layerfield] = fieldString
}
}
var str = ''
if (searchfields.hasOwnProperty(layer.options.layerName)) {
var sf = searchfields[layer.options.layerName] //sf for search field
for (var i = 0; i < sf.length; i++) {
str += sf[i][1]
str += ' '
}
}
str = str.substring(0, str.length - 1)
var searchFieldTokens = str.split(' ')
var searchStr
if (searchFieldTokens.length == 2) {
if (
searchFieldTokens[0].toLowerCase() ==
layer.useKeyAsName.toLowerCase()
) {
searchStr = keyAsName + ' ' + layer.feature.properties.Sol
} else {
searchStr = layer.feature.properties.Sol + ' ' + keyAsName
}
}
QueryURL.writeSearchURL([searchStr], layer.options.layerName)
})
}
//Pretty much like makePointLayer but without the pointToLayer stuff
async function makeVectorLayer(
layerObj,
evenIfOff,
useEmptyGeoJSON,
forceGeoJSON
) {
return new Promise((resolve, reject) => {
if (forceGeoJSON) add(forceGeoJSON)
else
captureVector(
layerObj,
{ evenIfOff: evenIfOff, useEmptyGeoJSON: useEmptyGeoJSON },
add,
(f) => {
Map_.map.on('moveend', f)
if (
layerObj.time?.enabled === true &&
layerObj.controlled !== true
)
L_.subscribeTimeChange(
`dynamicextent_${layerObj.name}`,
f
)
L_.subscribeOnSpecificLayerToggle(
`dynamicextent_${layerObj.name}`,
layerObj.name,
f
)
}
)
function add(data, allowInvalid) {
data = F_.parseIntoGeoJSON(data)
let invalidGeoJSONTrace = gjv.valid(data, true)
const allowableErrors = [`position must only contain numbers`]
invalidGeoJSONTrace = invalidGeoJSONTrace.filter((t) => {
if (typeof t !== 'string') return false
for (let i = 0; i < allowableErrors.length; i++) {
if (t.toLowerCase().indexOf(allowableErrors[i]) != -1)
return false
}
return true
})
if (
data == null ||
data === 'off' ||
(invalidGeoJSONTrace.length > 0 && allowInvalid !== true)
) {
if (data != null && data != 'off') {
data = null
console.warn(
`ERROR: ${layerObj.display_name} has invalid GeoJSON!`
)
}
L_._layersLoaded[
L_._layersOrdered.indexOf(layerObj.name)
] = true
L_.layers.layer[layerObj.name] = data == null ? null : false
allLayersLoaded()
resolve()
return
}
layerObj.style = layerObj.style || {}
layerObj.style.layerName = layerObj.name
layerObj.style.opacity = L_.layers.opacity[layerObj.name]
//layerObj.style.fillOpacity = L_.layers.opacity[layerObj.name]
const vl = constructVectorLayer(
data,
layerObj,
onEachFeatureDefault,
Map_
)
L_.layers.attachments[layerObj.name] = vl.sublayers
L_.layers.layer[layerObj.name] = vl.layer
d3.selectAll('.' + F_.getSafeName(layerObj.name)).data(
data.features
)
L_._layersLoaded[L_._layersOrdered.indexOf(layerObj.name)] = true
allLayersLoaded()
resolve()
}
})
}
//For vector velocity layers
async function makeVelocityLayer(
layerObj,
evenIfOff,
useEmptyGeoJSON,
forceGeoJSON
) {
return new Promise((resolve, reject) => {
if (forceGeoJSON) add(forceGeoJSON)
else
captureVector(
layerObj,
{ evenIfOff: evenIfOff, useEmptyGeoJSON: useEmptyGeoJSON },
add,
(f) => {
Map_.map.on('moveend', f)
if (
layerObj.time?.enabled === true &&
layerObj.controlled !== true
)
L_.subscribeTimeChange(
`dynamicgeodataset_${layerObj.name}`,
f
)
L_.subscribeOnSpecificLayerToggle(
`dynamicgeodataset_${layerObj.name}`,
layerObj.name,
f
)
}
)
function add(data, allowInvalid) {
if (layerObj.type == 'velocity') {
if (
layerObj.kind == 'streamlines' ||
'kind' in layerObj == false
) {
const defaultColors = [
'rgb(36,104, 180)',
'rgb(60,157, 194)',
'rgb(128,205,193 )',
'rgb(151,218,168 )',
'rgb(198,231,181)',
'rgb(238,247,217)',
'rgb(255,238,159)',
'rgb(252,217,125)',
'rgb(255,182,100)',
'rgb(252,150,75)',
'rgb(250,112,52)',
'rgb(245,64,32)',
'rgb(237,45,28)',
'rgb(220,24,32)',
'rgb(180,0,35)',
]
let colorScale = ''
if (layerObj.variables?.streamlines?.colorScale) {
let colorConfig =
layerObj.variables?.streamlines?.colorScale
if (colorConfig.includes(',')) {
colorScale = colorConfig
.split('", "')
.map((item) => item.replace(/["]/g, ''))
} else if (colorConfig === 'DEFAULT') {
colorScale = defaultColors
} else {
// Assume we have a colormap name and look up the values
let reverse = false
if (colorConfig.endsWith('_r')) {
reverse = true
colorConfig = colorConfig.slice(0, -2)
}
colorScale = []
let colors = colormapData[colorConfig]?.colors
if (colors != null) {
colors
.map((color) => {
const r = Math.round(color[0] * 255)
const g = Math.round(color[1] * 255)
const b = Math.round(color[2] * 255)
return `rgb(${r}, ${g}, ${b})`
})
.forEach((colorString) =>
colorScale.push(colorString)
)
if (reverse) {
colorScale = colorScale.reverse()