-
Notifications
You must be signed in to change notification settings - Fork 353
/
Leaflet.ts
1186 lines (1074 loc) · 39.5 KB
/
Leaflet.ts
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 i18next from "i18next";
import {
action,
autorun,
computed,
observable,
reaction,
runInAction,
makeObservable
} from "mobx";
import { computedFn } from "mobx-utils";
import cesiumCancelAnimationFrame from "terriajs-cesium/Source/Core/cancelAnimationFrame";
import Cartesian2 from "terriajs-cesium/Source/Core/Cartesian2";
import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3";
import Cartographic from "terriajs-cesium/Source/Core/Cartographic";
import Clock from "terriajs-cesium/Source/Core/Clock";
import defaultValue from "terriajs-cesium/Source/Core/defaultValue";
import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid";
import EventHelper from "terriajs-cesium/Source/Core/EventHelper";
import CesiumMath from "terriajs-cesium/Source/Core/Math";
import Rectangle from "terriajs-cesium/Source/Core/Rectangle";
import cesiumRequestAnimationFrame from "terriajs-cesium/Source/Core/requestAnimationFrame";
import DataSource from "terriajs-cesium/Source/DataSources/DataSource";
import DataSourceCollection from "terriajs-cesium/Source/DataSources/DataSourceCollection";
import Entity from "terriajs-cesium/Source/DataSources/Entity";
import ImageryProvider from "terriajs-cesium/Source/Scene/ImageryProvider";
import SplitDirection from "terriajs-cesium/Source/Scene/SplitDirection";
import html2canvas from "terriajs-html2canvas";
import filterOutUndefined from "../Core/filterOutUndefined";
import isDefined from "../Core/isDefined";
import LatLonHeight from "../Core/LatLonHeight";
import runLater from "../Core/runLater";
import MapboxVectorTileImageryProvider from "../Map/ImageryProvider/MapboxVectorTileImageryProvider";
import ProtomapsImageryProvider from "../Map/ImageryProvider/ProtomapsImageryProvider";
import ImageryProviderLeafletGridLayer, {
isImageryProviderGridLayer as supportsImageryProviderGridLayer
} from "../Map/Leaflet/ImageryProviderLeafletGridLayer";
import ImageryProviderLeafletTileLayer from "../Map/Leaflet/ImageryProviderLeafletTileLayer";
import LeafletDataSourceDisplay from "../Map/Leaflet/LeafletDataSourceDisplay";
import LeafletScene from "../Map/Leaflet/LeafletScene";
import LeafletSelectionIndicator from "../Map/Leaflet/LeafletSelectionIndicator";
import LeafletVisualizer from "../Map/Leaflet/LeafletVisualizer";
import L from "../Map/LeafletPatched";
import PickedFeatures, {
ProviderCoords,
ProviderCoordsMap
} from "../Map/PickedFeatures/PickedFeatures";
import rectangleToLatLngBounds from "../Map/Vector/rectangleToLatLngBounds";
import FeatureInfoUrlTemplateMixin from "../ModelMixins/FeatureInfoUrlTemplateMixin";
import MappableMixin, {
ImageryParts,
MapItem
} from "../ModelMixins/MappableMixin";
import TileErrorHandlerMixin from "../ModelMixins/TileErrorHandlerMixin";
import ImageryProviderTraits from "../Traits/TraitsClasses/ImageryProviderTraits";
import SplitterTraits from "../Traits/TraitsClasses/SplitterTraits";
import TerriaViewer from "../ViewModels/TerriaViewer";
import CameraView from "./CameraView";
import hasTraits from "./Definition/hasTraits";
import TerriaFeature from "./Feature/Feature";
import GlobeOrMap from "./GlobeOrMap";
import { LeafletAttribution } from "./LeafletAttribution";
import MapInteractionMode from "./MapInteractionMode";
import Terria from "./Terria";
import { isUndefined } from "lodash-es";
import GeorasterTerriaLayer from "../Map/Leaflet/GeorasterTerriaLayer";
// We want TS to look at the type declared in lib/ThirdParty/terriajs-cesium-extra/index.d.ts
// and import doesn't allows us to do that, so instead we use require + type casting to ensure
// we still maintain the type checking, without TS screaming with errors
const FeatureDetection: FeatureDetection =
require("terriajs-cesium/Source/Core/FeatureDetection").default;
export type TerriaLeafletLayer =
| GeorasterTerriaLayer
| ImageryProviderLeafletGridLayer
| ImageryProviderLeafletTileLayer;
// This class is an observer. It probably won't contain any observables itself
export default class Leaflet extends GlobeOrMap {
readonly type = "Leaflet";
readonly terria: Terria;
readonly terriaViewer: TerriaViewer;
readonly map: L.Map;
readonly scene: LeafletScene;
readonly dataSources: DataSourceCollection = new DataSourceCollection();
readonly dataSourceDisplay: LeafletDataSourceDisplay;
readonly canShowSplitter = true;
private readonly _attributionControl: LeafletAttribution;
private readonly _leafletVisualizer: LeafletVisualizer;
private readonly _eventHelper: EventHelper;
private readonly _selectionIndicator: LeafletSelectionIndicator;
private _stopRequestAnimationFrame: boolean = false;
private _cesiumReqAnimFrameId: number | undefined;
private _pickedFeatures: PickedFeatures | undefined = undefined;
private _pauseMapInteractionCount = 0;
/* Disposers */
private readonly _disposeWorkbenchMapItemsSubscription: () => void;
private readonly _disposeDisableInteractionSubscription: () => void;
private _disposeSelectedFeatureSubscription?: () => void;
private _disposeSplitterReaction: () => void;
// These are used to split CesiumTileLayer and MapboxCanvasVectorTileLayer
@observable size: L.Point | undefined;
@observable nw: L.Point | undefined;
@observable se: L.Point | undefined;
@action
private updateMapObservables() {
this.size = this.map.getSize();
this.nw = this.map.containerPointToLayerPoint([0, 0]);
this.se = this.map.containerPointToLayerPoint(this.size);
}
private _createImageryLayer: (
ip: ImageryProvider,
clippingRectangle: Rectangle | undefined,
overrideCreateLeafletLayerFn: ImageryParts["overrideCreateLeafletLayer"]
) => TerriaLeafletLayer | undefined = computedFn(
(ip, clippingRectangle, overrideCreateLeafletLayerFn) => {
const layerOptions = {
bounds: clippingRectangle && rectangleToLatLngBounds(clippingRectangle)
};
// We have two different kinds of ImageryProviderLeaflet layers
// - Grid layer will use the ImageryProvider in the more traditional way - calling `requestImage` to draw the image on to a canvas
// - Tile layer will pass tile URLs to leaflet objects - which is a bit more "Leaflety" than Grid layer
// Tile layer is preferred. Grid layer mainly exists for custom Imagery Providers which aren't just a tile of image URLs
// Also, some kinds of Imagery Providers cannot create Leaflet layers appropriately, e.g. the COG Imagery Provider.
// In this case, the Catalog Item should specify an `overrideCreateLeafletLayer` property.
// If the Catalog Item defines `overrideCreateLeafletLayer` then use that, otherwise follow the logic below.
if (overrideCreateLeafletLayerFn) {
return overrideCreateLeafletLayerFn(ip, layerOptions.bounds);
} else if (supportsImageryProviderGridLayer(ip)) {
return new ImageryProviderLeafletGridLayer(this, ip, layerOptions);
} else {
return new ImageryProviderLeafletTileLayer(this, ip, layerOptions);
}
}
);
private _makeImageryLayerFromParts(
parts: ImageryParts,
item: MappableMixin.Instance
) {
if (TileErrorHandlerMixin.isMixedInto(item)) {
// because this code path can run multiple times, make sure we remove the
// handler if it is already registered
parts.imageryProvider.errorEvent.removeEventListener(
item.onTileLoadError,
item
);
parts.imageryProvider.errorEvent.addEventListener(
item.onTileLoadError,
item
);
}
return this._createImageryLayer(
parts.imageryProvider,
parts.clippingRectangle,
parts.overrideCreateLeafletLayer
);
}
constructor(terriaViewer: TerriaViewer, container: string | HTMLElement) {
super();
makeObservable(this);
this.terria = terriaViewer.terria;
this.terriaViewer = terriaViewer;
this.map = L.map(container, {
zoomControl: false,
attributionControl: false,
zoomSnap: 1, // Change to 0.2 for incremental zoom when Chrome fixes canvas scaling gaps
preferCanvas: true,
worldCopyJump: false
}).setView([-28.5, 135], 5);
this.map.on("move", () => this.updateMapObservables());
this.map.on("zoom", () => this.updateMapObservables());
this.scene = new LeafletScene(this.map);
this._attributionControl = new LeafletAttribution(this.terria);
this.map.addControl(this._attributionControl);
this._leafletVisualizer = new LeafletVisualizer();
this._selectionIndicator = new LeafletSelectionIndicator(this);
this.dataSourceDisplay = new LeafletDataSourceDisplay({
scene: this.scene,
dataSourceCollection: this.dataSources,
visualizersCallback: <any>this._leafletVisualizer.visualizersCallback // TODO: fix type error
});
this._eventHelper = new EventHelper();
this._eventHelper.add(this.terria.timelineClock.onTick, <any>((
clock: Clock
) => {
this.dataSourceDisplay.update(clock.currentTime);
}));
const ticker = () => {
if (!this._stopRequestAnimationFrame) {
this.terria.timelineClock.tick();
this._cesiumReqAnimFrameId = cesiumRequestAnimationFrame(ticker);
}
};
// Start ticker asynchronously to avoid calling an action in the consctructor
runLater(ticker);
this._disposeWorkbenchMapItemsSubscription = this.observeModelLayer();
this._disposeSplitterReaction = this._reactToSplitterChanges();
this._disposeDisableInteractionSubscription = autorun(() => {
const map = this.map;
const interactions = filterOutUndefined([
map.touchZoom,
map.doubleClickZoom,
map.scrollWheelZoom,
map.boxZoom,
map.keyboard,
map.dragging,
map.tap
]);
const pickLocation = this.pickLocation.bind(this);
const pickFeature = (entity: Entity, event: L.LeafletMouseEvent) => {
this._featurePicked(entity, event);
};
// Update mouse coords on mouse move
this.map.on("mousemove", (e: L.LeafletEvent) => {
const mouseEvent = <L.LeafletMouseEvent>e;
this.mouseCoords.updateCoordinatesFromLeaflet(
this.terria,
mouseEvent.originalEvent
);
});
if (this.terriaViewer.disableInteraction) {
interactions.forEach((handler) => handler.disable());
this.map.off("click", pickLocation);
this.scene.featureClicked.removeEventListener(pickFeature);
this._disposeSelectedFeatureSubscription &&
this._disposeSelectedFeatureSubscription();
} else {
interactions.forEach((handler) => handler.enable());
this.map.on("click", pickLocation);
this.scene.featureClicked.addEventListener(pickFeature);
this._disposeSelectedFeatureSubscription = autorun(() => {
const feature = this.terria.selectedFeature;
this._selectFeature(feature);
});
}
});
this._initProgressEvent();
}
get attributionPrefix() {
return this._attributionControl.prefix;
}
@computed
get attributions() {
return this._attributionControl.dataAttributions;
}
/**
* sets up loading listeners
*/
private _initProgressEvent() {
const onTileLoadChange = () => {
var tilesLoadingCount = 0;
this.map.eachLayer(function (layerOrGridlayer) {
// _tiles is protected but our knockout-loading-logic accesses it here anyway
const layer = layerOrGridlayer as any;
if (layer?._tiles) {
// Count all tiles not marked as loaded
tilesLoadingCount += Object.keys(layer._tiles).filter(
(key) => !layer._tiles[key].loaded
).length;
}
});
this._updateTilesLoadingCount(tilesLoadingCount);
};
this.map.on(
"layeradd",
function (evt: any) {
// This check makes sure we only watch tile layers, and also protects us if this private variable gets changed.
if (typeof evt.layer._tiles !== "undefined") {
evt.layer.on("tileloadstart tileload load", onTileLoadChange);
}
}.bind(this)
);
this.map.on(
"layerremove",
function (evt: any) {
evt.layer.off("tileloadstart tileload load", onTileLoadChange);
}.bind(this)
);
}
/**
* Pick feature from mouse click event.
*/
private pickLocation(e: L.LeafletEvent) {
const mouseEvent = <L.LeafletMouseEvent>e;
// Handle click events that cross the anti-meridian
if (mouseEvent.latlng.lng > 180 || mouseEvent.latlng.lng < -180) {
mouseEvent.latlng = mouseEvent.latlng.wrap();
}
// if (!this._dragboxcompleted && that.map.dragging.enabled()) {
this._pickFeatures(mouseEvent.latlng);
// }
// this._dragboxcompleted = false;
}
getContainer() {
return this.map.getContainer();
}
pauseMapInteraction() {
++this._pauseMapInteractionCount;
if (this._pauseMapInteractionCount === 1) {
this.map.dragging.disable();
}
}
resumeMapInteraction() {
--this._pauseMapInteractionCount;
if (this._pauseMapInteractionCount === 0) {
setTimeout(() => {
if (this._pauseMapInteractionCount === 0) {
this.map.dragging.enable();
}
}, 0);
}
}
destroy() {
this._disposeSelectedFeatureSubscription &&
this._disposeSelectedFeatureSubscription();
this._disposeSplitterReaction();
this._disposeWorkbenchMapItemsSubscription();
this._eventHelper.removeAll();
this._disposeDisableInteractionSubscription();
// This variable prevents a race condition if destroy() is called
// synchronously as a result of timelineClock ticking due to ticker()
this._stopRequestAnimationFrame = true;
if (isDefined(this._cesiumReqAnimFrameId)) {
cesiumCancelAnimationFrame(this._cesiumReqAnimFrameId);
}
this.dataSourceDisplay.destroy();
this.map.off("move");
this.map.off("zoom");
this.map.remove();
}
@computed
get availableCatalogItems() {
const catalogItems = [
...this.terriaViewer.items.get(),
this.terriaViewer.baseMap
];
return catalogItems;
}
@computed
get availableDataSources() {
const catalogItems = this.availableCatalogItems;
/* Handle datasources */
const allMapItems = ([] as MapItem[]).concat(
...catalogItems.filter(isDefined).map((item) => item.mapItems)
);
const dataSources = allMapItems.filter(isDataSource);
return dataSources;
}
private observeModelLayer() {
// Setup reaction to sync datSources collection with availableDataSources
//
// To avoid buggy concurrent syncs, we have to ensure that even when
// multiple sync reactions are triggered, we run them one after the
// other. To do this, we make each run of the reaction wait for the
// previous `syncDataSourcesPromise` to finish before starting itself.
let syncDataSourcesPromise: Promise<void> = Promise.resolve();
const dataSourcesReactionDisposer = reaction(
() => this.availableDataSources,
() => {
syncDataSourcesPromise = syncDataSourcesPromise
.then(async () => {
await this.syncDataSourceCollection(
this.availableDataSources,
this.dataSources
);
this.notifyRepaintRequired();
})
.catch(console.error);
},
{ fireImmediately: true }
);
// Reaction to sync imagery from model layer with cesium map
const imageryReactionDisposer = autorun(() => {
const catalogItems = this.availableCatalogItems;
// Flatmap
const allImageryMapItems = (
[] as {
item: MappableMixin.Instance;
parts: ImageryParts;
}[]
).concat(
...catalogItems
.filter(isDefined)
.map((item) =>
item.mapItems
.filter(ImageryParts.is)
.map((parts: ImageryParts) => ({ item, parts }))
)
);
const allImagery = filterOutUndefined(
allImageryMapItems.map(({ item, parts }) => {
if (hasTraits(item, ImageryProviderTraits, "leafletUpdateInterval")) {
(parts.imageryProvider as any)._leafletUpdateInterval =
item.leafletUpdateInterval;
}
const layer = this._makeImageryLayerFromParts(parts, item);
if (isDefined(layer)) {
return {
parts: parts,
layer: layer
};
} else {
return undefined;
}
})
);
// Delete imagery layers no longer in the model
this.map.eachLayer((mapLayer) => {
if (
isImageryLayer(mapLayer) ||
mapLayer instanceof ImageryProviderLeafletGridLayer
) {
const index = allImagery.findIndex((im) => im.layer === mapLayer);
if (index === -1) {
this.map.removeLayer(mapLayer);
}
}
});
// Add layer and update its zIndex
let zIndex = 100; // Start at an arbitrary value
allImagery.reverse().forEach(({ parts, layer }) => {
if (!isDefined(layer)) {
// TODO: Should we filter out undefined layers before this point in the code?
console.log(
`Layer is undefined, and will fail when trying to set Opacity. Skipping layer ${parts}`
);
debugger;
return;
}
if (parts.show) {
layer.setOpacity(parts.alpha);
layer.setZIndex(zIndex);
zIndex++;
// NB: these ts-ignores are because the type of GeoRaster is not well defined. It does implement the requires methods.
// @ts-ignore
if (!this.map.hasLayer(layer)) {
// @ts-ignore
this.map.addLayer(layer);
}
} else {
// @ts-ignore
this.map.removeLayer(layer);
}
});
});
return () => {
dataSourcesReactionDisposer();
imageryReactionDisposer();
};
}
/**
* Syncs the `dataSources` collection against the latest `availableDataSources`.
*
*/
private async syncDataSourceCollection(
availableDataSources: DataSource[],
dataSources: DataSourceCollection
) {
// 1. Remove deleted data sources
//
// Iterate backwards because we're removing items.
for (let i = dataSources.length - 1; i >= 0; i--) {
const ds = dataSources.get(i);
if (availableDataSources.indexOf(ds) === -1 || !ds.show) {
dataSources.remove(ds);
}
}
// 2. Add new data sources
for (let ds of availableDataSources) {
if (!dataSources.contains(ds) && ds.show) {
await dataSources.add(ds);
}
}
// 3. Ensure stacking order matches order in `availableDataSources` - first item appears on top.
runInAction(() =>
availableDataSources.forEach((ds) => {
// There is a buggy/un-intended side-effect when calling raiseToTop() with
// a source that doesn't exist in the collection. Doing this will replace
// the last entry in the collection with the new one. So we should be
// careful to raiseToTop() only if the DS already exists in the collection.
// Relevant code:
// https://github.com/CesiumGS/cesium/blob/dbd452328a48bfc4e192146862a9f8fa15789dc8/packages/engine/Source/DataSources/DataSourceCollection.js#L298-L299
dataSources.contains(ds) && dataSources.raiseToTop(ds);
})
);
}
doZoomTo(
target: CameraView | Rectangle | DataSource | MappableMixin.Instance | any,
flightDurationSeconds: number = 3.0
): Promise<void> {
if (!isDefined(target)) {
return Promise.resolve();
//throw new DeveloperError("target is required.");
}
let bounds;
// Target is a KML data source
if (isDefined(target.entities)) {
if (isDefined(this.dataSourceDisplay)) {
bounds = this.dataSourceDisplay.getLatLngBounds(target);
}
} else {
let extent;
if (target instanceof Rectangle) {
extent = target;
} else if (target instanceof CameraView) {
extent = target.rectangle;
} else if (MappableMixin.isMixedInto(target)) {
if (isDefined(target.cesiumRectangle)) {
extent = target.cesiumRectangle;
}
if (!isDefined(extent)) {
// Zoom to the first item!
return this.doZoomTo(target.mapItems[0], flightDurationSeconds);
}
} else {
/** TODO: THIS PATH IS FOLLOWED FOR COGS. Need to define target.rectangle...
* Needed to get the layer extent. Now storing this in clippingRectangle property of target, for COGs.
* TODO: Is that appropriate? **/
// Changed from:
// extent = target.rectangle;
extent = isDefined(target.rectangle)
? target.rectangle
: target.clippingRectangle;
}
// Account for a bounding box crossing the date line.
if (extent.east < extent.west) {
extent = Rectangle.clone(extent);
extent.east += CesiumMath.TWO_PI;
}
bounds = rectangleToLatLngBounds(extent);
}
if (isDefined(bounds)) {
this.map.flyToBounds(bounds, {
animate: flightDurationSeconds > 0.0,
duration: flightDurationSeconds
});
}
return Promise.resolve();
}
getCurrentCameraView(): CameraView {
const bounds = this.map.getBounds();
return new CameraView(
Rectangle.fromDegrees(
bounds.getWest(),
bounds.getSouth(),
bounds.getEast(),
bounds.getNorth()
)
);
}
notifyRepaintRequired() {
// No action necessary.
}
pickFromLocation(
latLngHeight: LatLonHeight,
providerCoords: ProviderCoordsMap,
existingFeatures: TerriaFeature[]
) {
this._pickFeatures(
L.latLng({
lat: latLngHeight.latitude,
lng: latLngHeight.longitude,
alt: latLngHeight.height
}),
providerCoords,
existingFeatures
);
}
/**
* Return features at a latitude, longitude and (optionally) height for the given imageryLayer.
* @param latLngHeight The position on the earth to pick
* @param providerCoords A map of imagery provider urls to the tile coords used to get features for those imagery
* @returns A flat array of all the features for the given tiles that are currently on the map
*/
@action
async getFeaturesAtLocation(
latLngHeight: LatLonHeight,
providerCoords: ProviderCoordsMap
) {
const pickMode = new MapInteractionMode({
message: i18next.t("models.imageryLayer.resolvingAvailability"),
onCancel: () => {
this.terria.mapInteractionModeStack.pop();
}
});
this.terria.mapInteractionModeStack.push(pickMode);
this._pickFeatures(
L.latLng({
lat: latLngHeight.latitude,
lng: latLngHeight.longitude,
alt: latLngHeight.height
}),
providerCoords,
[],
true
);
if (pickMode.pickedFeatures) {
const pickedFeatures = pickMode.pickedFeatures;
await pickedFeatures.allFeaturesAvailablePromise;
}
return runInAction(() => {
this.terria.mapInteractionModeStack.pop();
return pickMode.pickedFeatures?.features;
});
}
/*
* There are two "listeners" for clicks which are set up in our constructor.
* - One fires for any click: `map.on('click', ...`. It calls `pickFeatures`.
* - One fires only for vector features: `this.scene.featureClicked.addEventListener`.
* It calls `featurePicked`, which calls `pickFeatures` and then adds the feature it found, if any.
* These events can fire in either order.
* Billboards do not fire the first event.
*
* Note that `pickFeatures` does nothing if `leaflet._pickedFeatures` is already set.
* Otherwise, it sets it, runs `runLater` to clear it, and starts the asynchronous raster feature picking.
*
* So:
* If only the first event is received, it triggers the raster-feature picking as desired.
* If both are received in the order above, the second adds the vector features to the list of raster features as desired.
* If both are received in the reverse order, the vector-feature click kicks off the same behavior as the other click would have;
* and when the next click is received, it is ignored - again, as desired.
*/
@action
private _featurePicked(entity: Entity, event: L.LeafletMouseEvent) {
this._pickFeatures(event.latlng);
// Ignore clicks on the feature highlight.
if (entity.entityCollection && entity.entityCollection.owner) {
const owner = entity.entityCollection.owner;
if (
owner instanceof DataSource &&
owner.name == GlobeOrMap._featureHighlightName
) {
return;
}
}
const feature = TerriaFeature.fromEntityCollectionOrEntity(entity);
const catalogItem = feature._catalogItem;
if (
FeatureInfoUrlTemplateMixin.isMixedInto(catalogItem) &&
typeof catalogItem.getFeaturesFromPickResult === "function" &&
this.terria.allowFeatureInfoRequests
) {
const result = catalogItem.getFeaturesFromPickResult.bind(catalogItem)(
undefined,
entity,
(this._pickedFeatures?.features.length || 0) < catalogItem.maxRequests
);
if (result && isDefined(this._pickedFeatures)) {
if (Array.isArray(result)) {
this._pickedFeatures.features.push(...result);
} else {
this._pickedFeatures.features.push(result);
}
}
} else if (isDefined(this._pickedFeatures)) {
this._pickedFeatures.features.push(feature);
}
if (
isDefined(this._pickedFeatures) &&
isDefined(feature) &&
feature.position
) {
this._pickedFeatures.pickPosition = (<any>feature.position)._value;
}
}
private _pickFeatures(
latlng: L.LatLng,
tileCoordinates?: Record<string, ProviderCoords>,
existingFeatures?: TerriaFeature[],
ignoreSplitter: boolean = false
) {
if (isDefined(this._pickedFeatures)) {
// Picking is already in progress.
return;
}
this._pickedFeatures = new PickedFeatures();
if (isDefined(existingFeatures)) {
this._pickedFeatures.features = existingFeatures;
}
// We run this later because vector click events and the map click event can come through in any order, but we can
// be reasonably sure that all of them will be processed by the time our runLater func is invoked.
const cleanup = runLater(() => {
// Set this again just in case a vector pick came through and reset it to the vector's position.
const newPickLocation =
Ellipsoid.WGS84.cartographicToCartesian(pickedLocation);
runInAction(() => {
const mapInteractionModeStack = this.terria.mapInteractionModeStack;
if (
isDefined(mapInteractionModeStack) &&
mapInteractionModeStack.length > 0
) {
const pickedFeatures =
mapInteractionModeStack[mapInteractionModeStack.length - 1]
.pickedFeatures;
if (isDefined(pickedFeatures)) {
pickedFeatures.pickPosition = newPickLocation;
}
} else if (isDefined(this.terria.pickedFeatures)) {
this.terria.pickedFeatures.pickPosition = newPickLocation;
}
});
// Unset this so that the next click will start building features from scratch.
this._pickedFeatures = undefined;
});
const imageryLayers: ImageryProviderLeafletTileLayer[] = [];
if (this.terria.allowFeatureInfoRequests) {
this.map.eachLayer((layer) => {
if (isImageryLayer(layer)) {
imageryLayers.push(layer);
}
});
}
// we need items sorted in reverse order by their zIndex to get correct ordering of feature info
imageryLayers.sort(
(
a: ImageryProviderLeafletTileLayer,
b: ImageryProviderLeafletTileLayer
) => {
if (!isDefined(a.options.zIndex) || !isDefined(b.options.zIndex)) {
return 0;
}
if (a.options.zIndex < b.options.zIndex) {
return 1;
}
if (a.options.zIndex > b.options.zIndex) {
return -1;
}
return 0;
}
);
tileCoordinates = defaultValue(tileCoordinates, {});
const pickedLocation = Cartographic.fromDegrees(latlng.lng, latlng.lat);
this._pickedFeatures.pickPosition =
Ellipsoid.WGS84.cartographicToCartesian(pickedLocation);
const imageryFeaturePromises = imageryLayers.map(async (imageryLayer) => {
const imageryLayerUrl = (<any>imageryLayer.imageryProvider)?.url;
const longRadians = CesiumMath.toRadians(latlng.lng);
const latRadians = CesiumMath.toRadians(latlng.lat);
const coords =
tileCoordinates?.[imageryLayerUrl] ??
(await imageryLayer.getFeaturePickingCoords(
this.map,
longRadians,
latRadians
));
const features = await imageryLayer.pickFeatures(
coords.x,
coords.y,
coords.level,
longRadians,
latRadians
);
// Make sure ImageryLayerFeatureInfo has imagery layer property
features?.forEach((feature) => (feature.imageryLayer = imageryLayer));
return {
features: features,
imageryLayer: imageryLayer,
coords: coords
};
});
const pickedFeatures = this._pickedFeatures;
// We want the all available promise to return after the cleanup one to
// make sure all vector click events have resolved.
pickedFeatures.allFeaturesAvailablePromise = Promise.all([
cleanup,
Promise.all(imageryFeaturePromises)
.then((results) => {
runInAction(() => {
pickedFeatures.isLoading = false;
});
pickedFeatures.providerCoords = {};
const filteredResults = results.filter(
(result) => isDefined(result.features) && result.features.length > 0
);
pickedFeatures.providerCoords = filteredResults.reduce(function (
coordsSoFar: ProviderCoordsMap,
result
) {
const imageryProvider = result.imageryLayer?.imageryProvider;
if (imageryProvider)
coordsSoFar[(<any>imageryProvider).url] = result.coords;
return coordsSoFar;
},
{});
const features = filteredResults.reduce((allFeatures, result) => {
if (
this.terria.showSplitter &&
ignoreSplitter === false &&
isDefined(pickedFeatures.pickPosition)
) {
// Skip this feature, unless the imagery layer is on the picked side or
// belongs to both sides of the splitter
const screenPosition = this._computePositionOnScreen(
pickedFeatures.pickPosition
);
const pickedSide =
this._getSplitterSideForScreenPosition(screenPosition);
const layerDirection = result.imageryLayer.splitDirection;
if (
!(
layerDirection === pickedSide ||
layerDirection === SplitDirection.NONE
)
) {
return allFeatures;
}
}
return allFeatures.concat(
result.features!.map((feature) => {
// For features without a position, use the picked location.
if (!isDefined(feature.position)) {
feature.position = pickedLocation;
}
return this._createFeatureFromImageryLayerFeature(feature);
})
);
}, pickedFeatures.features);
runInAction(() => {
pickedFeatures.features = features;
});
})
.catch((e) => {
runInAction(() => {
pickedFeatures.isLoading = false;
pickedFeatures.error =
"An unknown error occurred while picking features.";
});
throw e;
})
]).then(() => undefined);
runInAction(() => {
const mapInteractionModeStack = this.terria.mapInteractionModeStack;
if (
isDefined(mapInteractionModeStack) &&
mapInteractionModeStack.length > 0
) {
mapInteractionModeStack[
mapInteractionModeStack.length - 1
].pickedFeatures = this._pickedFeatures;
} else {
this.terria.pickedFeatures = this._pickedFeatures;
}
});
}
_reactToSplitterChanges() {
return autorun(() => {
const items = this.terria.mainViewer.items.get();
const showSplitter = this.terria.showSplitter;
const splitPosition = this.terria.splitPosition;
items.forEach((item) => {
if (
MappableMixin.isMixedInto(item) &&
hasTraits(item, SplitterTraits, "splitDirection")
) {
const layers = this.getImageryLayersForItem(item);
const splitDirection = item.splitDirection;
layers.forEach(
action((layer) => {
if (showSplitter) {
layer.splitDirection = splitDirection;
layer.splitPosition = splitPosition;
} else {
layer.splitDirection = SplitDirection.NONE;
layer.splitPosition = splitPosition;
}
})
);
}
});
this.notifyRepaintRequired();
});
}
getImageryLayersForItem(
item: MappableMixin.Instance
): (
| ImageryProviderLeafletTileLayer
| ImageryProviderLeafletGridLayer
| GeorasterTerriaLayer
)[] {
return filterOutUndefined(
item.mapItems.map((m) => {
if (ImageryParts.is(m)) {
const layer = this._makeImageryLayerFromParts(m, item);
return layer ?? undefined;
}
})
);
}
/**
* Computes the screen position of a given world position.
* @param position The world position in Earth-centered Fixed coordinates.
* @param [result] The instance to which to copy the result.
* @return The screen position, or undefined if the position is not on the screen.
*/
private _computePositionOnScreen(
position: Cartesian3,
result?: Cartesian2
): Cartesian2 {
const cartographicScratch = new Cartographic();
const cartographic = Ellipsoid.WGS84.cartesianToCartographic(
position,
cartographicScratch
);
const point = this.map.latLngToContainerPoint(
L.latLng(
CesiumMath.toDegrees(cartographic.latitude),