-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Viewer.js
2408 lines (2177 loc) · 77.3 KB
/
Viewer.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
import BoundingSphere from "../../Core/BoundingSphere.js";
import Cartesian3 from "../../Core/Cartesian3.js";
import Cartographic from "../../Core/Cartographic.js";
import Clock from "../../Core/Clock.js";
import defaultValue from "../../Core/defaultValue.js";
import defer from "../../Core/defer.js";
import defined from "../../Core/defined.js";
import destroyObject from "../../Core/destroyObject.js";
import DeveloperError from "../../Core/DeveloperError.js";
import Event from "../../Core/Event.js";
import EventHelper from "../../Core/EventHelper.js";
import HeadingPitchRange from "../../Core/HeadingPitchRange.js";
import Matrix4 from "../../Core/Matrix4.js";
import ScreenSpaceEventType from "../../Core/ScreenSpaceEventType.js";
import BoundingSphereState from "../../DataSources/BoundingSphereState.js";
import ConstantPositionProperty from "../../DataSources/ConstantPositionProperty.js";
import DataSourceCollection from "../../DataSources/DataSourceCollection.js";
import DataSourceDisplay from "../../DataSources/DataSourceDisplay.js";
import Entity from "../../DataSources/Entity.js";
import EntityView from "../../DataSources/EntityView.js";
import Property from "../../DataSources/Property.js";
import Cesium3DTileset from "../../Scene/Cesium3DTileset.js";
import computeFlyToLocationForRectangle from "../../Scene/computeFlyToLocationForRectangle.js";
import ImageryLayer from "../../Scene/ImageryLayer.js";
import SceneMode from "../../Scene/SceneMode.js";
import TimeDynamicPointCloud from "../../Scene/TimeDynamicPointCloud.js";
import knockout from "../../ThirdParty/knockout.js";
import Animation from "../Animation/Animation.js";
import AnimationViewModel from "../Animation/AnimationViewModel.js";
import BaseLayerPicker from "../BaseLayerPicker/BaseLayerPicker.js";
import createDefaultImageryProviderViewModels from "../BaseLayerPicker/createDefaultImageryProviderViewModels.js";
import createDefaultTerrainProviderViewModels from "../BaseLayerPicker/createDefaultTerrainProviderViewModels.js";
import CesiumWidget from "../CesiumWidget/CesiumWidget.js";
import ClockViewModel from "../ClockViewModel.js";
import FullscreenButton from "../FullscreenButton/FullscreenButton.js";
import Geocoder from "../Geocoder/Geocoder.js";
import getElement from "../getElement.js";
import HomeButton from "../HomeButton/HomeButton.js";
import InfoBox from "../InfoBox/InfoBox.js";
import NavigationHelpButton from "../NavigationHelpButton/NavigationHelpButton.js";
import ProjectionPicker from "../ProjectionPicker/ProjectionPicker.js";
import SceneModePicker from "../SceneModePicker/SceneModePicker.js";
import SelectionIndicator from "../SelectionIndicator/SelectionIndicator.js";
import subscribeAndEvaluate from "../subscribeAndEvaluate.js";
import Timeline from "../Timeline/Timeline.js";
import VRButton from "../VRButton/VRButton.js";
import Cesium3DTileFeature from "../../Scene/Cesium3DTileFeature.js";
import JulianDate from "../../Core/JulianDate.js";
import CesiumMath from "../../Core/Math.js";
const boundingSphereScratch = new BoundingSphere();
function onTimelineScrubfunction(e) {
const clock = e.clock;
clock.currentTime = e.timeJulian;
clock.shouldAnimate = false;
}
function getCesium3DTileFeatureDescription(feature) {
const propertyNames = feature.getPropertyNames();
let html = "";
propertyNames.forEach(function (propertyName) {
const value = feature.getProperty(propertyName);
if (defined(value)) {
html += `<tr><th>${propertyName}</th><td>${value}</td></tr>`;
}
});
if (html.length > 0) {
html = `<table class="cesium-infoBox-defaultTable"><tbody>${html}</tbody></table>`;
}
return html;
}
function getCesium3DTileFeatureName(feature) {
// We need to iterate all property names to find potential
// candidates, but since we prefer some property names
// over others, we store them in an indexed array
// and then use the first defined element in the array
// as the preferred choice.
let i;
const possibleNames = [];
const propertyNames = feature.getPropertyNames();
for (i = 0; i < propertyNames.length; i++) {
const propertyName = propertyNames[i];
if (/^name$/i.test(propertyName)) {
possibleNames[0] = feature.getProperty(propertyName);
} else if (/name/i.test(propertyName)) {
possibleNames[1] = feature.getProperty(propertyName);
} else if (/^title$/i.test(propertyName)) {
possibleNames[2] = feature.getProperty(propertyName);
} else if (/^(id|identifier)$/i.test(propertyName)) {
possibleNames[3] = feature.getProperty(propertyName);
} else if (/element/i.test(propertyName)) {
possibleNames[4] = feature.getProperty(propertyName);
} else if (/(id|identifier)$/i.test(propertyName)) {
possibleNames[5] = feature.getProperty(propertyName);
}
}
const length = possibleNames.length;
for (i = 0; i < length; i++) {
const item = possibleNames[i];
if (defined(item) && item !== "") {
return item;
}
}
return "Unnamed Feature";
}
function pickEntity(viewer, e) {
const picked = viewer.scene.pick(e.position);
if (defined(picked)) {
const id = defaultValue(picked.id, picked.primitive.id);
if (id instanceof Entity) {
return id;
}
if (picked instanceof Cesium3DTileFeature) {
return new Entity({
name: getCesium3DTileFeatureName(picked),
description: getCesium3DTileFeatureDescription(picked),
feature: picked,
});
}
}
// No regular entity picked. Try picking features from imagery layers.
if (defined(viewer.scene.globe)) {
return pickImageryLayerFeature(viewer, e.position);
}
}
const scratchStopTime = new JulianDate();
function trackDataSourceClock(timeline, clock, dataSource) {
if (defined(dataSource)) {
const dataSourceClock = dataSource.clock;
if (defined(dataSourceClock)) {
dataSourceClock.getValue(clock);
if (defined(timeline)) {
const startTime = dataSourceClock.startTime;
let stopTime = dataSourceClock.stopTime;
// When the start and stop times are equal, set the timeline to the shortest interval
// starting at the start time. This prevents an invalid timeline configuration.
if (JulianDate.equals(startTime, stopTime)) {
stopTime = JulianDate.addSeconds(
startTime,
CesiumMath.EPSILON2,
scratchStopTime
);
}
timeline.updateFromClock();
timeline.zoomTo(startTime, stopTime);
}
}
}
}
const cartesian3Scratch = new Cartesian3();
function pickImageryLayerFeature(viewer, windowPosition) {
const scene = viewer.scene;
const pickRay = scene.camera.getPickRay(windowPosition);
const imageryLayerFeaturePromise = scene.imageryLayers.pickImageryLayerFeatures(
pickRay,
scene
);
if (!defined(imageryLayerFeaturePromise)) {
return;
}
// Imagery layer feature picking is asynchronous, so put up a message while loading.
const loadingMessage = new Entity({
id: "Loading...",
description: "Loading feature information...",
});
imageryLayerFeaturePromise.then(
function (features) {
// Has this async pick been superseded by a later one?
if (viewer.selectedEntity !== loadingMessage) {
return;
}
if (!defined(features) || features.length === 0) {
viewer.selectedEntity = createNoFeaturesEntity();
return;
}
// Select the first feature.
const feature = features[0];
const entity = new Entity({
id: feature.name,
description: feature.description,
});
if (defined(feature.position)) {
const ecfPosition = viewer.scene.globe.ellipsoid.cartographicToCartesian(
feature.position,
cartesian3Scratch
);
entity.position = new ConstantPositionProperty(ecfPosition);
}
viewer.selectedEntity = entity;
},
function () {
// Has this async pick been superseded by a later one?
if (viewer.selectedEntity !== loadingMessage) {
return;
}
viewer.selectedEntity = createNoFeaturesEntity();
}
);
return loadingMessage;
}
function createNoFeaturesEntity() {
return new Entity({
id: "None",
description: "No features found.",
});
}
function enableVRUI(viewer, enabled) {
const geocoder = viewer._geocoder;
const homeButton = viewer._homeButton;
const sceneModePicker = viewer._sceneModePicker;
const projectionPicker = viewer._projectionPicker;
const baseLayerPicker = viewer._baseLayerPicker;
const animation = viewer._animation;
const timeline = viewer._timeline;
const fullscreenButton = viewer._fullscreenButton;
const infoBox = viewer._infoBox;
const selectionIndicator = viewer._selectionIndicator;
const visibility = enabled ? "hidden" : "visible";
if (defined(geocoder)) {
geocoder.container.style.visibility = visibility;
}
if (defined(homeButton)) {
homeButton.container.style.visibility = visibility;
}
if (defined(sceneModePicker)) {
sceneModePicker.container.style.visibility = visibility;
}
if (defined(projectionPicker)) {
projectionPicker.container.style.visibility = visibility;
}
if (defined(baseLayerPicker)) {
baseLayerPicker.container.style.visibility = visibility;
}
if (defined(animation)) {
animation.container.style.visibility = visibility;
}
if (defined(timeline)) {
timeline.container.style.visibility = visibility;
}
if (
defined(fullscreenButton) &&
fullscreenButton.viewModel.isFullscreenEnabled
) {
fullscreenButton.container.style.visibility = visibility;
}
if (defined(infoBox)) {
infoBox.container.style.visibility = visibility;
}
if (defined(selectionIndicator)) {
selectionIndicator.container.style.visibility = visibility;
}
if (viewer._container) {
const right =
enabled || !defined(fullscreenButton)
? 0
: fullscreenButton.container.clientWidth;
viewer._vrButton.container.style.right = `${right}px`;
viewer.forceResize();
}
}
/**
* @typedef {Object} Viewer.ConstructorOptions
*
* Initialization options for the Viewer constructor
*
* @property {Boolean} [animation=true] If set to false, the Animation widget will not be created.
* @property {Boolean} [baseLayerPicker=true] If set to false, the BaseLayerPicker widget will not be created.
* @property {Boolean} [fullscreenButton=true] If set to false, the FullscreenButton widget will not be created.
* @property {Boolean} [vrButton=false] If set to true, the VRButton widget will be created.
* @property {Boolean|GeocoderService[]} [geocoder=true] If set to false, the Geocoder widget will not be created.
* @property {Boolean} [homeButton=true] If set to false, the HomeButton widget will not be created.
* @property {Boolean} [infoBox=true] If set to false, the InfoBox widget will not be created.
* @property {Boolean} [sceneModePicker=true] If set to false, the SceneModePicker widget will not be created.
* @property {Boolean} [selectionIndicator=true] If set to false, the SelectionIndicator widget will not be created.
* @property {Boolean} [timeline=true] If set to false, the Timeline widget will not be created.
* @property {Boolean} [navigationHelpButton=true] If set to false, the navigation help button will not be created.
* @property {Boolean} [navigationInstructionsInitiallyVisible=true] True if the navigation instructions should initially be visible, or false if the should not be shown until the user explicitly clicks the button.
* @property {Boolean} [scene3DOnly=false] When <code>true</code>, each geometry instance will only be rendered in 3D to save GPU memory.
* @property {Boolean} [shouldAnimate=false] <code>true</code> if the clock should attempt to advance simulation time by default, <code>false</code> otherwise. This option takes precedence over setting {@link Viewer#clockViewModel}.
* @property {ClockViewModel} [clockViewModel=new ClockViewModel(clock)] The clock view model to use to control current time.
* @property {ProviderViewModel} [selectedImageryProviderViewModel] The view model for the current base imagery layer, if not supplied the first available base layer is used. This value is only valid if `baseLayerPicker` is set to true.
* @property {ProviderViewModel[]} [imageryProviderViewModels=createDefaultImageryProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker. This value is only valid if `baseLayerPicker` is set to true.
* @property {ProviderViewModel} [selectedTerrainProviderViewModel] The view model for the current base terrain layer, if not supplied the first available base layer is used. This value is only valid if `baseLayerPicker` is set to true.
* @property {ProviderViewModel[]} [terrainProviderViewModels=createDefaultTerrainProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker. This value is only valid if `baseLayerPicker` is set to true.
* @property {ImageryProvider} [imageryProvider=createWorldImagery()] The imagery provider to use. This value is only valid if `baseLayerPicker` is set to false.
* @property {TerrainProvider} [terrainProvider=new EllipsoidTerrainProvider()] The terrain provider to use
* @property {SkyBox|false} [skyBox] The skybox used to render the stars. When <code>undefined</code>, the default stars are used. If set to <code>false</code>, no skyBox, Sun, or Moon will be added.
* @property {SkyAtmosphere|false} [skyAtmosphere] Blue sky, and the glow around the Earth's limb. Set to <code>false</code> to turn it off.
* @property {Element|String} [fullscreenElement=document.body] The element or id to be placed into fullscreen mode when the full screen button is pressed.
* @property {Boolean} [useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
* @property {Number} [targetFrameRate] The target frame rate when using the default render loop.
* @property {Boolean} [showRenderLoopErrors=true] If true, this widget will automatically display an HTML panel to the user containing the error, if a render loop error occurs.
* @property {Boolean} [useBrowserRecommendedResolution=true] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
* @property {Boolean} [automaticallyTrackDataSourceClocks=true] If true, this widget will automatically track the clock settings of newly added DataSources, updating if the DataSource's clock changes. Set this to false if you want to configure the clock independently.
* @property {Object} [contextOptions] Context and WebGL creation properties corresponding to <code>options</code> passed to {@link Scene}.
* @property {SceneMode} [sceneMode=SceneMode.SCENE3D] The initial scene mode.
* @property {MapProjection} [mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
* @property {Globe|false} [globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene. If set to <code>false</code>, no globe will be added.
* @property {Boolean} [orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
* @property {Element|String} [creditContainer] The DOM element or ID that will contain the {@link CreditDisplay}. If not specified, the credits are added to the bottom of the widget itself.
* @property {Element|String} [creditViewport] The DOM element or ID that will contain the credit pop up created by the {@link CreditDisplay}. If not specified, it will appear over the widget itself.
* @property {DataSourceCollection} [dataSources=new DataSourceCollection()] The collection of data sources visualized by the widget. If this parameter is provided,
* the instance is assumed to be owned by the caller and will not be destroyed when the viewer is destroyed.
* @property {Boolean} [shadows=false] Determines if shadows are cast by light sources.
* @property {ShadowMode} [terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from light sources.
* @property {MapMode2D} [mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
* @property {Boolean} [projectionPicker=false] If set to true, the ProjectionPicker widget will be created.
* @property {Boolean} [requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling reduces the CPU/GPU usage of your application and uses less battery on mobile, but requires using {@link Scene#requestRender} to render a new frame explicitly in this mode. This will be necessary in many cases after making changes to the scene in other parts of the API. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
* @property {Number} [maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
* @property {Number} [depthPlaneEllipsoidOffset=0.0] Adjust the DepthPlane to address rendering artefacts below ellipsoid zero elevation.
* @property {Number} [msaaSamples=1] If provided, this value controls the rate of multisample antialiasing. Typical multisampling rates are 2, 4, and sometimes 8 samples per pixel. Higher sampling rates of MSAA may impact performance in exchange for improved visual quality. This value only applies to WebGL2 contexts that support multisample render targets.
*/
/**
* A base widget for building applications. It composites all of the standard Cesium widgets into one reusable package.
* The widget can always be extended by using mixins, which add functionality useful for a variety of applications.
*
* @alias Viewer
* @constructor
*
* @param {Element|String} container The DOM element or ID that will contain the widget.
* @param {Viewer.ConstructorOptions} [options] Object describing initialization options
*
* @exception {DeveloperError} Element with id "container" does not exist in the document.
* @exception {DeveloperError} options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.imageryProvider instead.
* @exception {DeveloperError} options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.terrainProvider instead.
*
* @see Animation
* @see BaseLayerPicker
* @see CesiumWidget
* @see FullscreenButton
* @see HomeButton
* @see SceneModePicker
* @see Timeline
* @see viewerDragDropMixin
*
* @demo {@link https://sandcastle.cesium.com/index.html?src=Hello%20World.html|Cesium Sandcastle Hello World Demo}
*
* @example
* //Initialize the viewer widget with several custom options and mixins.
* const viewer = new Cesium.Viewer('cesiumContainer', {
* //Start in Columbus Viewer
* sceneMode : Cesium.SceneMode.COLUMBUS_VIEW,
* //Use Cesium World Terrain
* terrainProvider : Cesium.createWorldTerrain(),
* //Hide the base layer picker
* baseLayerPicker : false,
* //Use OpenStreetMaps
* imageryProvider : new Cesium.OpenStreetMapImageryProvider({
* url : 'https://a.tile.openstreetmap.org/'
* }),
* skyBox : new Cesium.SkyBox({
* sources : {
* positiveX : 'stars/TychoSkymapII.t3_08192x04096_80_px.jpg',
* negativeX : 'stars/TychoSkymapII.t3_08192x04096_80_mx.jpg',
* positiveY : 'stars/TychoSkymapII.t3_08192x04096_80_py.jpg',
* negativeY : 'stars/TychoSkymapII.t3_08192x04096_80_my.jpg',
* positiveZ : 'stars/TychoSkymapII.t3_08192x04096_80_pz.jpg',
* negativeZ : 'stars/TychoSkymapII.t3_08192x04096_80_mz.jpg'
* }
* }),
* // Show Columbus View map with Web Mercator projection
* mapProjection : new Cesium.WebMercatorProjection()
* });
*
* //Add basic drag and drop functionality
* viewer.extend(Cesium.viewerDragDropMixin);
*
* //Show a pop-up alert if we encounter an error when processing a dropped file
* viewer.dropError.addEventListener(function(dropHandler, name, error) {
* console.log(error);
* window.alert(error);
* });
*/
function Viewer(container, options) {
//>>includeStart('debug', pragmas.debug);
if (!defined(container)) {
throw new DeveloperError("container is required.");
}
//>>includeEnd('debug');
container = getElement(container);
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
const createBaseLayerPicker =
(!defined(options.globe) || options.globe !== false) &&
(!defined(options.baseLayerPicker) || options.baseLayerPicker !== false);
//>>includeStart('debug', pragmas.debug);
// If not using BaseLayerPicker, selectedImageryProviderViewModel is an invalid option
if (
!createBaseLayerPicker &&
defined(options.selectedImageryProviderViewModel)
) {
throw new DeveloperError(
"options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget. \
Either specify options.imageryProvider instead or set options.baseLayerPicker to true."
);
}
// If not using BaseLayerPicker, selectedTerrainProviderViewModel is an invalid option
if (
!createBaseLayerPicker &&
defined(options.selectedTerrainProviderViewModel)
) {
throw new DeveloperError(
"options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget. \
Either specify options.terrainProvider instead or set options.baseLayerPicker to true."
);
}
//>>includeEnd('debug')
const that = this;
const viewerContainer = document.createElement("div");
viewerContainer.className = "cesium-viewer";
container.appendChild(viewerContainer);
// Cesium widget container
const cesiumWidgetContainer = document.createElement("div");
cesiumWidgetContainer.className = "cesium-viewer-cesiumWidgetContainer";
viewerContainer.appendChild(cesiumWidgetContainer);
// Bottom container
const bottomContainer = document.createElement("div");
bottomContainer.className = "cesium-viewer-bottom";
viewerContainer.appendChild(bottomContainer);
const scene3DOnly = defaultValue(options.scene3DOnly, false);
let clock;
let clockViewModel;
let destroyClockViewModel = false;
if (defined(options.clockViewModel)) {
clockViewModel = options.clockViewModel;
clock = clockViewModel.clock;
} else {
clock = new Clock();
clockViewModel = new ClockViewModel(clock);
destroyClockViewModel = true;
}
if (defined(options.shouldAnimate)) {
clock.shouldAnimate = options.shouldAnimate;
}
// Cesium widget
const cesiumWidget = new CesiumWidget(cesiumWidgetContainer, {
imageryProvider:
createBaseLayerPicker || defined(options.imageryProvider)
? false
: undefined,
clock: clock,
skyBox: options.skyBox,
skyAtmosphere: options.skyAtmosphere,
sceneMode: options.sceneMode,
mapProjection: options.mapProjection,
globe: options.globe,
orderIndependentTranslucency: options.orderIndependentTranslucency,
contextOptions: options.contextOptions,
useDefaultRenderLoop: options.useDefaultRenderLoop,
targetFrameRate: options.targetFrameRate,
showRenderLoopErrors: options.showRenderLoopErrors,
useBrowserRecommendedResolution: options.useBrowserRecommendedResolution,
creditContainer: defined(options.creditContainer)
? options.creditContainer
: bottomContainer,
creditViewport: options.creditViewport,
scene3DOnly: scene3DOnly,
shadows: options.shadows,
terrainShadows: options.terrainShadows,
mapMode2D: options.mapMode2D,
requestRenderMode: options.requestRenderMode,
maximumRenderTimeChange: options.maximumRenderTimeChange,
depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
msaaSamples: options.msaaSamples,
});
let dataSourceCollection = options.dataSources;
let destroyDataSourceCollection = false;
if (!defined(dataSourceCollection)) {
dataSourceCollection = new DataSourceCollection();
destroyDataSourceCollection = true;
}
const scene = cesiumWidget.scene;
const dataSourceDisplay = new DataSourceDisplay({
scene: scene,
dataSourceCollection: dataSourceCollection,
});
const eventHelper = new EventHelper();
eventHelper.add(clock.onTick, Viewer.prototype._onTick, this);
eventHelper.add(scene.morphStart, Viewer.prototype._clearTrackedObject, this);
// Selection Indicator
let selectionIndicator;
if (
!defined(options.selectionIndicator) ||
options.selectionIndicator !== false
) {
const selectionIndicatorContainer = document.createElement("div");
selectionIndicatorContainer.className =
"cesium-viewer-selectionIndicatorContainer";
viewerContainer.appendChild(selectionIndicatorContainer);
selectionIndicator = new SelectionIndicator(
selectionIndicatorContainer,
scene
);
}
// Info Box
let infoBox;
if (!defined(options.infoBox) || options.infoBox !== false) {
const infoBoxContainer = document.createElement("div");
infoBoxContainer.className = "cesium-viewer-infoBoxContainer";
viewerContainer.appendChild(infoBoxContainer);
infoBox = new InfoBox(infoBoxContainer);
const infoBoxViewModel = infoBox.viewModel;
eventHelper.add(
infoBoxViewModel.cameraClicked,
Viewer.prototype._onInfoBoxCameraClicked,
this
);
eventHelper.add(
infoBoxViewModel.closeClicked,
Viewer.prototype._onInfoBoxClockClicked,
this
);
}
// Main Toolbar
const toolbar = document.createElement("div");
toolbar.className = "cesium-viewer-toolbar";
viewerContainer.appendChild(toolbar);
// Geocoder
let geocoder;
if (!defined(options.geocoder) || options.geocoder !== false) {
const geocoderContainer = document.createElement("div");
geocoderContainer.className = "cesium-viewer-geocoderContainer";
toolbar.appendChild(geocoderContainer);
let geocoderService;
if (defined(options.geocoder) && typeof options.geocoder !== "boolean") {
geocoderService = Array.isArray(options.geocoder)
? options.geocoder
: [options.geocoder];
}
geocoder = new Geocoder({
container: geocoderContainer,
geocoderServices: geocoderService,
scene: scene,
});
// Subscribe to search so that we can clear the trackedEntity when it is clicked.
eventHelper.add(
geocoder.viewModel.search.beforeExecute,
Viewer.prototype._clearObjects,
this
);
}
// HomeButton
let homeButton;
if (!defined(options.homeButton) || options.homeButton !== false) {
homeButton = new HomeButton(toolbar, scene);
if (defined(geocoder)) {
eventHelper.add(homeButton.viewModel.command.afterExecute, function () {
const viewModel = geocoder.viewModel;
viewModel.searchText = "";
if (viewModel.isSearchInProgress) {
viewModel.search();
}
});
}
// Subscribe to the home button beforeExecute event so that we can clear the trackedEntity.
eventHelper.add(
homeButton.viewModel.command.beforeExecute,
Viewer.prototype._clearTrackedObject,
this
);
}
// SceneModePicker
// By default, we silently disable the scene mode picker if scene3DOnly is true,
// but if sceneModePicker is explicitly set to true, throw an error.
//>>includeStart('debug', pragmas.debug);
if (options.sceneModePicker === true && scene3DOnly) {
throw new DeveloperError(
"options.sceneModePicker is not available when options.scene3DOnly is set to true."
);
}
//>>includeEnd('debug');
let sceneModePicker;
if (
!scene3DOnly &&
(!defined(options.sceneModePicker) || options.sceneModePicker !== false)
) {
sceneModePicker = new SceneModePicker(toolbar, scene);
}
let projectionPicker;
if (options.projectionPicker) {
projectionPicker = new ProjectionPicker(toolbar, scene);
}
// BaseLayerPicker
let baseLayerPicker;
let baseLayerPickerDropDown;
if (createBaseLayerPicker) {
const imageryProviderViewModels = defaultValue(
options.imageryProviderViewModels,
createDefaultImageryProviderViewModels()
);
const terrainProviderViewModels = defaultValue(
options.terrainProviderViewModels,
createDefaultTerrainProviderViewModels()
);
baseLayerPicker = new BaseLayerPicker(toolbar, {
globe: scene.globe,
imageryProviderViewModels: imageryProviderViewModels,
selectedImageryProviderViewModel:
options.selectedImageryProviderViewModel,
terrainProviderViewModels: terrainProviderViewModels,
selectedTerrainProviderViewModel:
options.selectedTerrainProviderViewModel,
});
//Grab the dropdown for resize code.
const elements = toolbar.getElementsByClassName(
"cesium-baseLayerPicker-dropDown"
);
baseLayerPickerDropDown = elements[0];
}
// These need to be set after the BaseLayerPicker is created in order to take effect
if (defined(options.imageryProvider) && options.imageryProvider !== false) {
if (createBaseLayerPicker) {
baseLayerPicker.viewModel.selectedImagery = undefined;
}
scene.imageryLayers.removeAll();
scene.imageryLayers.addImageryProvider(options.imageryProvider);
}
if (defined(options.terrainProvider)) {
if (createBaseLayerPicker) {
baseLayerPicker.viewModel.selectedTerrain = undefined;
}
scene.terrainProvider = options.terrainProvider;
}
// Navigation Help Button
let navigationHelpButton;
if (
!defined(options.navigationHelpButton) ||
options.navigationHelpButton !== false
) {
let showNavHelp = true;
try {
//window.localStorage is null if disabled in Firefox or undefined in browsers with implementation
if (defined(window.localStorage)) {
const hasSeenNavHelp = window.localStorage.getItem(
"cesium-hasSeenNavHelp"
);
if (defined(hasSeenNavHelp) && Boolean(hasSeenNavHelp)) {
showNavHelp = false;
} else {
window.localStorage.setItem("cesium-hasSeenNavHelp", "true");
}
}
} catch (e) {
//Accessing window.localStorage throws if disabled in Chrome
//window.localStorage.setItem throws if in Safari private browsing mode or in any browser if we are over quota.
}
navigationHelpButton = new NavigationHelpButton({
container: toolbar,
instructionsInitiallyVisible: defaultValue(
options.navigationInstructionsInitiallyVisible,
showNavHelp
),
});
}
// Animation
let animation;
if (!defined(options.animation) || options.animation !== false) {
const animationContainer = document.createElement("div");
animationContainer.className = "cesium-viewer-animationContainer";
viewerContainer.appendChild(animationContainer);
animation = new Animation(
animationContainer,
new AnimationViewModel(clockViewModel)
);
}
// Timeline
let timeline;
if (!defined(options.timeline) || options.timeline !== false) {
const timelineContainer = document.createElement("div");
timelineContainer.className = "cesium-viewer-timelineContainer";
viewerContainer.appendChild(timelineContainer);
timeline = new Timeline(timelineContainer, clock);
timeline.addEventListener("settime", onTimelineScrubfunction, false);
timeline.zoomTo(clock.startTime, clock.stopTime);
}
// Fullscreen
let fullscreenButton;
let fullscreenSubscription;
let fullscreenContainer;
if (
!defined(options.fullscreenButton) ||
options.fullscreenButton !== false
) {
fullscreenContainer = document.createElement("div");
fullscreenContainer.className = "cesium-viewer-fullscreenContainer";
viewerContainer.appendChild(fullscreenContainer);
fullscreenButton = new FullscreenButton(
fullscreenContainer,
options.fullscreenElement
);
//Subscribe to fullscreenButton.viewModel.isFullscreenEnabled so
//that we can hide/show the button as well as size the timeline.
fullscreenSubscription = subscribeAndEvaluate(
fullscreenButton.viewModel,
"isFullscreenEnabled",
function (isFullscreenEnabled) {
fullscreenContainer.style.display = isFullscreenEnabled
? "block"
: "none";
if (defined(timeline)) {
timeline.container.style.right = `${fullscreenContainer.clientWidth}px`;
timeline.resize();
}
}
);
}
// VR
let vrButton;
let vrSubscription;
let vrModeSubscription;
if (options.vrButton) {
const vrContainer = document.createElement("div");
vrContainer.className = "cesium-viewer-vrContainer";
viewerContainer.appendChild(vrContainer);
vrButton = new VRButton(vrContainer, scene, options.fullScreenElement);
vrSubscription = subscribeAndEvaluate(
vrButton.viewModel,
"isVREnabled",
function (isVREnabled) {
vrContainer.style.display = isVREnabled ? "block" : "none";
if (defined(fullscreenButton)) {
vrContainer.style.right = `${fullscreenContainer.clientWidth}px`;
}
if (defined(timeline)) {
timeline.container.style.right = `${vrContainer.clientWidth}px`;
timeline.resize();
}
}
);
vrModeSubscription = subscribeAndEvaluate(
vrButton.viewModel,
"isVRMode",
function (isVRMode) {
enableVRUI(that, isVRMode);
}
);
}
//Assign all properties to this instance. No "this" assignments should
//take place above this line.
this._baseLayerPickerDropDown = baseLayerPickerDropDown;
this._fullscreenSubscription = fullscreenSubscription;
this._vrSubscription = vrSubscription;
this._vrModeSubscription = vrModeSubscription;
this._dataSourceChangedListeners = {};
this._automaticallyTrackDataSourceClocks = defaultValue(
options.automaticallyTrackDataSourceClocks,
true
);
this._container = container;
this._bottomContainer = bottomContainer;
this._element = viewerContainer;
this._cesiumWidget = cesiumWidget;
this._selectionIndicator = selectionIndicator;
this._infoBox = infoBox;
this._dataSourceCollection = dataSourceCollection;
this._destroyDataSourceCollection = destroyDataSourceCollection;
this._dataSourceDisplay = dataSourceDisplay;
this._clockViewModel = clockViewModel;
this._destroyClockViewModel = destroyClockViewModel;
this._toolbar = toolbar;
this._homeButton = homeButton;
this._sceneModePicker = sceneModePicker;
this._projectionPicker = projectionPicker;
this._baseLayerPicker = baseLayerPicker;
this._navigationHelpButton = navigationHelpButton;
this._animation = animation;
this._timeline = timeline;
this._fullscreenButton = fullscreenButton;
this._vrButton = vrButton;
this._geocoder = geocoder;
this._eventHelper = eventHelper;
this._lastWidth = 0;
this._lastHeight = 0;
this._allowDataSourcesToSuspendAnimation = true;
this._entityView = undefined;
this._enableInfoOrSelection = defined(infoBox) || defined(selectionIndicator);
this._clockTrackedDataSource = undefined;
this._trackedEntity = undefined;
this._needTrackedEntityUpdate = false;
this._selectedEntity = undefined;
this._zoomIsFlight = false;
this._zoomTarget = undefined;
this._zoomPromise = undefined;
this._zoomOptions = undefined;
this._selectedEntityChanged = new Event();
this._trackedEntityChanged = new Event();
knockout.track(this, [
"_trackedEntity",
"_selectedEntity",
"_clockTrackedDataSource",
]);
//Listen to data source events in order to track clock changes.
eventHelper.add(
dataSourceCollection.dataSourceAdded,
Viewer.prototype._onDataSourceAdded,
this
);
eventHelper.add(
dataSourceCollection.dataSourceRemoved,
Viewer.prototype._onDataSourceRemoved,
this
);
// Prior to each render, check if anything needs to be resized.
eventHelper.add(scene.postUpdate, Viewer.prototype.resize, this);
eventHelper.add(scene.postRender, Viewer.prototype._postRender, this);
// We need to subscribe to the data sources and collections so that we can clear the
// tracked object when it is removed from the scene.
// Subscribe to current data sources
const dataSourceLength = dataSourceCollection.length;
for (let i = 0; i < dataSourceLength; i++) {
this._dataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
}
this._dataSourceAdded(undefined, dataSourceDisplay.defaultDataSource);
// Hook up events so that we can subscribe to future sources.
eventHelper.add(
dataSourceCollection.dataSourceAdded,
Viewer.prototype._dataSourceAdded,
this
);
eventHelper.add(
dataSourceCollection.dataSourceRemoved,
Viewer.prototype._dataSourceRemoved,
this
);
// Subscribe to left clicks and zoom to the picked object.
function pickAndTrackObject(e) {
const entity = pickEntity(that, e);
if (defined(entity)) {
//Only track the entity if it has a valid position at the current time.
if (
Property.getValueOrUndefined(entity.position, that.clock.currentTime)
) {
that.trackedEntity = entity;
} else {
that.zoomTo(entity);
}
} else if (defined(that.trackedEntity)) {
that.trackedEntity = undefined;
}
}
function pickAndSelectObject(e) {
that.selectedEntity = pickEntity(that, e);
}
cesiumWidget.screenSpaceEventHandler.setInputAction(
pickAndSelectObject,
ScreenSpaceEventType.LEFT_CLICK
);
cesiumWidget.screenSpaceEventHandler.setInputAction(
pickAndTrackObject,
ScreenSpaceEventType.LEFT_DOUBLE_CLICK
);
}
Object.defineProperties(Viewer.prototype, {
/**
* Gets the parent container.
* @memberof Viewer.prototype
* @type {Element}
* @readonly
*/
container: {
get: function () {
return this._container;
},
},
/**
* Gets the DOM element for the area at the bottom of the window containing the
* {@link CreditDisplay} and potentially other things.
* @memberof Viewer.prototype
* @type {Element}
* @readonly
*/
bottomContainer: {
get: function () {
return this._bottomContainer;
},
},
/**
* Gets the CesiumWidget.
* @memberof Viewer.prototype
* @type {CesiumWidget}
* @readonly
*/
cesiumWidget: {
get: function () {
return this._cesiumWidget;
},
},
/**
* Gets the selection indicator.
* @memberof Viewer.prototype
* @type {SelectionIndicator}
* @readonly
*/
selectionIndicator: {
get: function () {
return this._selectionIndicator;
},
},
/**
* Gets the info box.
* @memberof Viewer.prototype
* @type {InfoBox}
* @readonly
*/
infoBox: {
get: function () {
return this._infoBox;
},
},
/**
* Gets the Geocoder.
* @memberof Viewer.prototype
* @type {Geocoder}
* @readonly
*/
geocoder: {
get: function () {