-
Notifications
You must be signed in to change notification settings - Fork 372
/
Terria.js
1298 lines (1159 loc) · 42 KB
/
Terria.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
"use strict";
/*global require*/
var URI = require("urijs");
import "./i18n.js";
var buildModuleUrl = require("terriajs-cesium/Source/Core/buildModuleUrl")
.default;
var CesiumEvent = require("terriajs-cesium/Source/Core/Event").default;
var combine = require("terriajs-cesium/Source/Core/combine").default;
var DataSourceCollection = require("terriajs-cesium/Source/DataSources/DataSourceCollection")
.default;
var defaultValue = require("terriajs-cesium/Source/Core/defaultValue").default;
var defined = require("terriajs-cesium/Source/Core/defined").default;
var DeveloperError = require("terriajs-cesium/Source/Core/DeveloperError")
.default;
var ImagerySplitDirection = require("terriajs-cesium/Source/Scene/ImagerySplitDirection")
.default;
var knockout = require("terriajs-cesium/Source/ThirdParty/knockout").default;
var queryToObject = require("terriajs-cesium/Source/Core/queryToObject")
.default;
var Rectangle = require("terriajs-cesium/Source/Core/Rectangle").default;
var when = require("terriajs-cesium/Source/ThirdParty/when").default;
var { addMarker } = require("./LocationMarkerUtils.js");
var CameraView = require("./CameraView");
var Catalog = require("./Catalog");
var Clock = require("./Clock");
var ConsoleAnalytics = require("../Core/ConsoleAnalytics");
var CorsProxy = require("../Core/CorsProxy");
var Feature = require("./Feature");
var GoogleAnalytics = require("../Core/GoogleAnalytics");
var hashEntity = require("../Core/hashEntity");
var isCommonMobilePlatform = require("../Core/isCommonMobilePlatform");
var loadJson5 = require("../Core/loadJson5");
var NoViewer = require("./NoViewer");
var NowViewing = require("./NowViewing");
var runLater = require("../Core/runLater");
var ServerConfig = require("../Core/ServerConfig");
var Services = require("./Services");
var TimeSeriesStack = require("./TimeSeriesStack");
var ViewerMode = require("./ViewerMode");
var findIndex = require("../Core/findIndex.js");
var i18next = require("i18next").default;
var overrides = require("../Overrides/defaults.jsx").overrides;
var defaultConfigParameters = {
defaultMaximumShownFeatureInfos: 100,
/* These services are not included within Terria, but this is where we expect them to be, by default. */
regionMappingDefinitionsUrl: "build/TerriaJS/data/regionMapping.json",
conversionServiceBaseUrl: "convert/",
proj4ServiceBaseUrl: "proj4/",
corsProxyBaseUrl: "proxy/",
proxyableDomainsUrl: "proxyabledomains/",
shareUrl: "share",
feedbackUrl: undefined,
initFragmentPaths: ["init/"],
storyEnabled: true,
interceptBrowserPrint: true,
useCesiumIonTerrain: true,
useCesiumIonBingImagery: undefined,
cesiumIonAccessToken: undefined,
cesiumTerrainUrl: undefined
};
// These properties can be directly passed in as properties of an init source.
var directInitSourceProperties = [
"baseMapName",
"fogSettings",
"splitPosition"
];
/**
* The overall model for TerriaJS.
* @alias Terria
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {String} options.baseUrl The base directory in which TerriaJS can find its static assets.
* @param {String} [options.cesiumBaseUrl='(options.baseUrl)/build/Cesium/build/'] The base directory in which Cesium can find its static assets.
* @param {String} [options.appName] The name of the app.
* @param {String} [options.supportEmail] The support email for the app.
* @param {AddressGeocoder} [options.batchGeocoder] Geocoder to use for geocoding addresses in CSV files.
*/
var Terria = function(options) {
if (!defined(options) || !defined(options.baseUrl)) {
throw new DeveloperError("options.baseUrl is required.");
}
options.functionOverrides = defined(options.functionOverrides)
? options.functionOverrides
: {};
this.overrides = combine(options.functionOverrides, overrides);
this.baseUrl = defaultValue(options.baseUrl, "build/TerriaJS/");
if (this.baseUrl.lastIndexOf("/") !== this.baseUrl.length - 1) {
this.baseUrl += "/";
}
var cesiumBaseUrl = defaultValue(
options.cesiumBaseUrl,
this.baseUrl + "build/Cesium/build/"
);
if (cesiumBaseUrl.lastIndexOf("/") !== cesiumBaseUrl.length - 1) {
cesiumBaseUrl += "/";
}
this.cesiumBaseUrl = cesiumBaseUrl;
buildModuleUrl.setBaseUrl(cesiumBaseUrl);
/**
* Gets or sets the instance to which to report Google Analytics-style log events.
* If a global `ga` function is defined, this defaults to `GoogleAnalytics`. Otherwise, it defaults
* to `ConsoleAnalytics`.
* @type {ConsoleAnalytics|GoogleAnalytics}
*/
this.analytics = options.analytics;
if (!defined(this.analytics)) {
if (typeof window !== "undefined" && defined(window.ga)) {
this.analytics = new GoogleAnalytics();
} else {
this.analytics = new ConsoleAnalytics();
}
}
/**
* The name of the app to be built upon Terria. This will appear in error messages to the user.
* @type {String}
* @default "TerriaJS App"
*/
this.appName = defaultValue(options.appName, "TerriaJS App");
/**
* The support email for the app to be built upon Terria. This will appear in error messages to the user.
* @type {String}
* @default "[email protected]"
*/
this.supportEmail = defaultValue(options.supportEmail, "[email protected]");
/**
* Indicates whether time-dynamic layers should start animating immediately upon load.
* If false, the user will need to press play manually before the layer starts animating.
* @type {Boolean}
* @default true
*/
this.autoPlay = false;
/**
* The geocoder to use for batch geocoding addresses in CSV files.
* @type {AddressGeocoder}
*/
this.batchGeocoder = options.batchGeocoder;
/**
* An event that is raised when a user-facing error occurs. This is especially useful for errors that happen asynchronously and so
* cannot be raised as an exception because no one would be able to catch it. Subscribers are passed the {@link TerriaError}
* that occurred as the only function parameter.
* @type {CesiumEvent}
*/
this.error = new CesiumEvent();
/**
* Gets or sets the map mode.
* @type {ViewerMode}
*/
this.viewerMode = defaultValue(options.viewerMode, ViewerMode.CesiumTerrain);
/**
* Gets or sets the current base map.
* @type {ImageryLayerCatalogItem}
*/
this.baseMap = undefined;
/**
* Gets or sets the current fog settings, used in the Cesium Scene/Fog constructor.
* @type {Object}
*/
this.fogSettings = undefined;
/**
* Gets or sets the name of the base map to use.
* @type {String}
*/
this.baseMapName = undefined;
/**
* Gets or sets a color that contrasts well with the base map.
* @type {String}
*/
this.baseMapContrastColor = "#ffffff";
/**
* Gets or sets the event that is raised just before switching between Cesium and Leaflet.
* @type {Event}
*/
this.beforeViewerChanged = new CesiumEvent();
/**
* Gets or sets the event that is raised just after switching between Cesium and Leaflet.
* @type {Event}
*/
this.afterViewerChanged = new CesiumEvent();
/**
* Gets or sets the collection of Cesium-style data sources that are currently active on the map.
* @type {DataSourceCollection}
*/
this.dataSources = new DataSourceCollection();
/**
* Gets or sets the clock that controls how time-varying data items are displayed.
* @type {Clock}
*/
this.clock = new Clock({
shouldAnimate: false
});
this.timeSeriesStack = new TimeSeriesStack(this.clock);
// See the intialView property below.
this._initialView = undefined;
/**
* Gets or sets the camera's home view. The home view is the one that the application
* returns to when the user clicks the "Reset View" button in the Navigation widget. It is also used
* as the {@link Terria#initialView} if one is not specified.
* @type {CameraView}
*/
this.homeView = new CameraView(Rectangle.MAX_VALUE);
/**
* Gets or sets a value indicating whether the application should automatically zoom to the new view when
* the {@link Terria#initialView} (or {@link Terria#homeView} if no initial view is specified).
* @type {Boolean}
* @default true
*/
this.zoomWhenInitialViewChanges = true;
/**
* Gets or sets the {@link this.corsProxy} used to determine if a URL needs to be proxied and to proxy it if necessary.
* @type {CorsProxy}
*/
this.corsProxy = new CorsProxy();
/**
* Gets or sets properties related to the Cesium globe. If the application is in 2D mode, this property will be
* undefined and {@link Terria#leaflet} will be set.
* @type {Cesium}
*/
this.cesium = undefined;
/**
* Gets or sets properties related to the Leaflet map. If the application is in 3D mode, this property will be
* undefined and {@link Terria#cesium} will be set.
* @type {Leaflet}
*/
this.leaflet = undefined;
this._noViewer = new NoViewer(this);
/**
* Gets or sets a reference to the current viewer, which is a subclass of {@link Terria#globeOrMap} -
* typically {@link Terria#cesium} or {@link Terria#leaflet}.
* This property is observable.
* @type {Cesium|Leaflet|NoViewer}
*/
this.currentViewer = this._noViewer;
/**
* Gets or sets the collection of user properties. User properties
* can be set by specifying them in the hash portion of the URL. For example, if the application URL is
* `http://localhost:3001/#foo=bar&someproperty=true`, this object will contain a property named 'foo' with the
* value 'bar' and a property named 'someproperty' with the value 'true'. Currently recognised URL parameters include
* 'map=[2D,3D]' (choose the Leaflet or Cesium view) and `mode=preview` (suppress warnings, when used as an embedded
* previewer).
* @type {Object}
*/
this.userProperties = {};
/**
* Gets or sets the list of sources from which the catalog was populated. A source may be a string, in which case it
* is expected to be a URL of an init file (like init_nm.json), or it can be a JSON-style object literal which is
* the init content itself.
* @type {Array}
*/
this.initSources = [];
/**
* Gets or sets the data source that represents the location marker.
* @type {CustomDataSource}
*/
this.locationMarker = undefined;
/**
* Gets or sets the features that are currently picked.
* @type {PickedFeatures}
*/
this.pickedFeatures = undefined;
/**
* Gets or sets whether to make feature info requests when points are clicked.
* @type {Boolean}
*/
this.allowFeatureInfoRequests = true;
/**
* Gets or sets the stack of map interactions modes. The mode at the top of the stack
* (highest index) handles click interactions with the map
* @type {MapInteractionMode[]}
*/
this.mapInteractionModeStack = [];
/**
* Gets or sets the catalog of geospatial data.
* @type {Catalog}
*/
this.catalog = new Catalog(this);
/**
* Gets or sets the add-on services known to the application.
* @type {Services}
*/
this.services = new Services(this);
/**
* Gets or sets the collection of geospatial data that is currently enabled.
* @type {NowViewing}
*/
this.nowViewing = new NowViewing(this);
/**
* Gets or sets the currently-selected feature, or undefined if there is no selected feature. The selected
* feature is highlighted by drawing a targetting cursor around it.
* @type {Entity}
*/
this.selectedFeature = undefined;
/**
* Gets or sets the configuration parameters set at startup.
* Contains:
* * regionMappingDefinitionsUrl: URL of JSON file containing region mapping definitions
* * conversionServiceBaseUrl: URL of OGR2OGR conversion service
* * proj4ServiceBaseUrl: URL of proj4def lookup service
* * corsProxyBaseUrl: URL of CORS proxy
* @type {Object}
*/
this.configParameters = defaultConfigParameters;
/**
* Gets or sets the urlShorter to be used with terria. This is currently set in the start method
* to allow the urlShortener object to properly initialize. See the GoogleUrlShortener for an
* example urlShortener.
* @type {Object}
*/
this.urlShortener = undefined;
/**
* Gets or sets the shareDataService to be used with Terria, which can save JSON or (in future) other user-provided
* data somewhere. It can be used to generate short URLs.
* @type {Object}
*/
this.shareDataService = undefined;
/**
* Gets or sets the ServerConfig object representing server-side configuration.
* @type {Object}
*/
this.serverConfig = undefined;
/**
* Event that tracks changes to the progress in loading new tiles from either Cesium or Leaflet - events will be
* raised with the number of tiles that still need to load.
*
* @type {CesiumEvent}
*/
this.tileLoadProgressEvent = new CesiumEvent();
this.disclaimerListener = function(catalogMember, callback) {
window.alert(catalogMember.initialMessage.content); /*eslint no-alert: 0*/
callback();
};
/**
* Gets or sets the selectBox function - set true when user requires a rectangle parameter from analytics.
* @type {Boolean}
*/
this.selectBox = false;
/**
* Gets or sets a callback function that can modify any "start data" (e.g. a share URL) before it is loaded.
* The function is passed the start data and may modify it in place or return a new instance.
* @type {Function}
*/
this.filterStartDataCallback = undefined;
/**
* Gets or sets whether to show a splitter, if possible. Default false. This property is observable.
* @type {Boolean}
*/
this.showSplitter = false;
/**
* Gets or sets whether to toggle viewState's sharedFromExplorerPanel after loading start data. Default false.
* @type {Boolean}
*/
this.sharedFromExplorerPanel = false;
/**
* Gets or sets id of previewed item
* @type {string}
*/
this.previewedItemId = undefined;
/**
* Gets or sets the current position of the splitter (if {@link Terria#showSplitter} is true) as a fraction of the map window.
* 0.0 is on the left, 0.5 is in the center, and 1.0 is on the right. This property is observable.
*/
this.splitPosition = 0.5;
/**
* Gets or sets the current vertical position of the splitter (if {@link Terria#showSplitter} is true) as a fraction of the map window.
* 0.0 is on the top, 0.5 is in the center, and 1.0 is on the bottom. This property is observable.
*/
this.splitPositionVertical = 0.5;
/**
* Array of stories
*/
this.stories = [];
/**
* Base ratio for maximumScreenSpaceError
* @type {Integer}
*/
this.baseMaximumScreenSpaceError = 2;
/**
* Gets or sets whether to use the device's native resolution (sets cesium.viewer.resolutionScale to a ratio of devicePixelRatio)
* @type {Boolean}
*/
this.useNativeResolution = false;
/**
* Gets or sets whether we should initiate the satellite guidance, based on
* whether a time wms exists in NowViewing
* @type {Boolean}
*/
this.shouldStartSatelliteGuidance = false;
knockout.track(this, [
"baseMaximumScreenSpaceError",
"useNativeResolution",
"viewerMode",
"baseMap",
"baseMapName",
"fogSettings",
"_initialView",
"homeView",
"locationMarker",
"pickedFeatures",
"selectedFeature",
"mapInteractionModeStack",
"configParameters",
"catalog",
"selectBox",
"currentViewer",
"showSplitter",
"splitPosition",
"splitPositionVertical",
"baseMapContrastColor",
"sharedFromExplorerPanel",
"previewedItemId",
"stories",
"shouldStartSatelliteGuidance"
]);
/**
* Gets or sets the camera's initial view. This is the view that the application has at startup. If this property
* is not explicitly specified, the {@link Terria#homeView} is used.
* @type {CameraView}
*/
knockout.defineProperty(this, "initialView", {
get: function() {
if (this._initialView) {
return this._initialView;
} else {
return this.homeView;
}
},
set: function(value) {
this._initialView = value;
}
});
knockout.getObservable(this, "initialView").subscribe(function() {
if (this.zoomWhenInitialViewChanges && defined(this.currentViewer)) {
this.currentViewer.zoomTo(this.initialView, 2.0);
}
}, this);
var myEventAdd = window.attachEvent || window.addEventListener;
var myEventRemove = window.detachEvent || window.removeEventListener;
var chkevent = window.attachEvent ? "onbeforeunload" : "beforeunload"; // make IE7, IE8 compitable
this.handleWindowClose = function(e) {
var confirmationMessage = "Are you sure to leave the page?";
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
};
knockout.getObservable(this, "stories").subscribe(function() {
if (this.stories.length > 0) {
myEventAdd(chkevent, this.handleWindowClose);
// window.addEventListener("beforeunload", this.handleWindowClose);
} else {
myEventRemove(chkevent, this.handleWindowClose);
//window.removeEventListener("beforeunload", this.handleWindowClose);
}
}, this);
};
/**
* Starts up Terria.
*
* @param {Object} options Object with the following properties:
* @param {String} [options.applicationUrl] The URL of the application. Typically this is obtained from window.location. This URL, if
* supplied, is parsed for startup parameters.
* @param {String} [options.configUrl='config.json'] The URL of the file containing configuration information, such as the list of domains to proxy.
* @param {UrlShortener} [options.urlShortener] The URL shortener to use to expand short URLs. If this property is undefined, short URLs will not be expanded.
* @param {Boolean} [options.persistViewerMode] Whether to use the ViewerMode stored in localStorage if avaliable (this takes priority over other ViewerMode options). If not specified the stored ViewerMode will be used.
*/
Terria.prototype.start = function(options) {
function slashify(url) {
return url && url[url.length - 1] !== "/" ? url + "/" : url;
}
this.catalog.isLoading = true;
var applicationUrl = defaultValue(options.applicationUrl, "");
this.urlShortener = options.urlShortener;
this.shareDataService = options.shareDataService;
var that = this;
return loadJson5(options.configUrl).then(function(config) {
if (defined(config.parameters)) {
// allow config file to provide TerriaJS-Server URLs to facilitate purely static deployments relying on external services
that.configParameters = combine(config.parameters, that.configParameters);
}
var cp = that.configParameters;
cp.conversionServiceBaseUrl = slashify(cp.conversionServiceBaseUrl);
cp.proj4ServiceBaseUrl = slashify(cp.proj4ServiceBaseUrl);
cp.corsProxyBaseUrl = slashify(cp.corsProxyBaseUrl);
that.appName = defaultValue(
cp.appName,
defaultValue(options.appName, that.appName)
);
that.supportEmail = defaultValue(
cp.supportEmail,
defaultValue(options.supportEmail, that.supportEmail)
);
if (defined(cp.autoPlay)) that.autoPlay = cp.autoPlay;
that.analytics.start(that.configParameters);
that.analytics.logEvent(
"launch",
"url",
defined(applicationUrl.href) ? applicationUrl.href : "empty"
);
var initializationUrls = config.initializationUrls;
if (defined(initializationUrls)) {
for (var i = 0; i < initializationUrls.length; i++) {
that.initSources.push(generateInitializationUrl(initializationUrls[i]));
}
}
showDisclaimer(
that,
options.globalDisclaimerHtml,
options.developmentDisclaimerPreambleHtml
);
that.serverConfig = new ServerConfig();
let serverConfig;
return that.serverConfig
.init(cp.serverConfigUrl)
.then(function() {
// All the "proxyableDomains" bits here are due to a pre-serverConfig mechanism for whitelisting domains.
// We should deprecate it.
var pdu = that.configParameters.proxyableDomainsUrl;
if (pdu) {
return loadJson5(pdu);
}
})
.then(function(proxyableDomains) {
if (proxyableDomains) {
// format of proxyableDomains JSON file slightly differs from serverConfig format.
proxyableDomains.allowProxyFor =
proxyableDomains.allowProxyFor || proxyableDomains.proxyableDomains;
}
if (typeof that.serverConfig === "object") {
serverConfig = that.serverConfig.config; // if server config is unavailable, this remains undefined.
}
if (that.shareDataService) {
that.shareDataService.init(serverConfig);
}
that.corsProxy.init(
proxyableDomains || serverConfig,
cp.corsProxyBaseUrl,
config.proxyDomains
);
})
.otherwise(function(e) {
console.error(e);
// There's no particular reason an error should be thrown here.
that.error.raiseEvent({
title: i18next.t("models.terria.initErrorTitle"),
message: i18next.t("models.terria.initErrorMessage")
});
})
.then(function() {
return that.updateApplicationUrl(applicationUrl, that.urlShortener);
})
.then(function() {
var persistViewerMode = defaultValue(options.persistViewerMode, true);
if (persistViewerMode && defined(that.getLocalProperty("viewermode"))) {
that.viewerMode = parseInt(that.getLocalProperty("viewermode"), 10);
} else {
// If we are running on a mobile platform set the viewerMode to the config specified default mobile viewer mode.
if (isCommonMobilePlatform() && !defined(that.userProperties.map)) {
// This is the default viewerMode to use if the configuration parameter is not set or is not set correctly.
that.viewerMode = ViewerMode.Leaflet;
if (
defined(that.configParameters.mobileDefaultViewerMode) &&
typeof that.configParameters.mobileDefaultViewerMode === "string"
) {
const mobileDefault = that.configParameters.mobileDefaultViewerMode.toLowerCase();
if (mobileDefault === "3dterrain") {
that.viewerMode = ViewerMode.CesiumTerrain;
} else if (mobileDefault === "3dsmooth") {
that.viewerMode = ViewerMode.CesiumEllipsoid;
} else if (mobileDefault === "2d") {
that.viewerMode = ViewerMode.Leaflet;
}
}
}
if (options.defaultTo2D && !defined(that.userProperties.map)) {
that.viewerMode = ViewerMode.Leaflet;
}
}
that.catalog.isLoading = false;
})
.otherwise(function(e) {
console.error("Error from updateApplicationUrl: ", e);
that.error.raiseEvent({
title: i18next.t("models.terria.urlLoadErrorTitle"),
message: i18next.t("models.terria.urlLoadErrorMessage")
});
});
});
};
/**
* Updates the state of the application based on the hash portion of a URL.
* @param {String} newUrl The new URL of the application.
* @return {Promise} A promise that resolves when any new init sources specified in the URL have been loaded.
*/
Terria.prototype.updateApplicationUrl = function(newUrl) {
var uri = new URI(newUrl);
var hash = uri.fragment();
var hashProperties = queryToObject(hash);
var initSources = this.initSources.slice();
var promise = interpretHash(
this,
hashProperties,
this.userProperties,
this.initSources,
initSources
);
var that = this;
return when(promise).then(function() {
var desiredMode = (that.userProperties.map || "").toLowerCase();
if (desiredMode === "2d") {
that.viewerMode = ViewerMode.Leaflet;
} else if (desiredMode === "3d") {
that.viewerMode = ViewerMode.CesiumTerrain;
} else if (desiredMode === "3dsmooth") {
that.viewerMode = ViewerMode.CesiumEllipsoid;
}
return loadInitSources(that, initSources);
});
};
Terria.prototype.updateFromStartData = function(startData) {
var initSources = this.initSources.slice();
interpretStartData(this, startData, this.initSources, initSources);
return loadInitSources(this, initSources);
};
/**
* Gets the value of a user property. If the property doesn't exist, it is created as an observable property with the
* value undefined. This way, if it becomes defined in the future, anyone depending on the value will be notified.
* @param {String} propertyName The name of the user property for which to get the value.
* @return {Object} The value of the property, or undefined if the property does not exist.
*/
Terria.prototype.getUserProperty = function(propertyName) {
if (!knockout.getObservable(this.userProperties, propertyName)) {
this.userProperties[propertyName] = undefined;
knockout.track(this.userProperties, [propertyName]);
}
return this.userProperties[propertyName];
};
Terria.prototype.addInitSource = function(initSource, fromStory = false) {
var promise = when();
var that = this;
var viewerChangeListener;
function zoomToInitialView() {
that.currentViewer.zoomTo(that.initialView, 0.0);
if (defined(viewerChangeListener)) {
viewerChangeListener();
}
}
// Extract the list of CORS-ready domains.
if (defined(initSource.corsDomains)) {
this.corsProxy.corsDomains.push.apply(
this.corsProxy.corsDomains,
initSource.corsDomains
);
}
// The last init source to specify an initial/home camera view wins.
if (defined(initSource.homeCamera)) {
this.homeView = CameraView.fromJson(initSource.homeCamera);
}
if (defined(initSource.initialCamera)) {
this.initialView = CameraView.fromJson(initSource.initialCamera);
}
// Extract the init source properties that require no deserialization.
directInitSourceProperties.forEach(function(propertyName) {
// a special case for basemap
if (propertyName === "baseMapName" && defined(initSource[propertyName])) {
// if basemap name is not set, we check terria.basemap to see if the
// same basemap is already active
if (
defined(that.baseMap) &&
that.baseMap.name === initSource[propertyName]
) {
return;
}
}
if (
defined(initSource[propertyName]) &&
initSource[propertyName] !== that[propertyName]
) {
that[propertyName] = initSource[propertyName];
}
});
if (defined(initSource.sharedFromExplorerPanel)) {
if (initSource.sharedFromExplorerPanel) {
that.sharedFromExplorerPanel = true;
}
}
if (defined(initSource.previewedItemId)) {
that.previewedItemId = initSource.previewedItemId;
}
if (defined(initSource.showSplitter)) {
// If you try to show the splitter straight away, the browser hangs.
runLater(function() {
that.showSplitter = initSource.showSplitter;
});
}
if (fromStory === true) {
viewerChangeListener = this.afterViewerChanged.addEventListener(
zoomToInitialView
);
}
if (defined(initSource.viewerMode) && !defined(this.userProperties.map)) {
var desiredMode = (initSource.viewerMode || "").toLowerCase();
if (desiredMode === "2d") {
if (fromStory && this.viewerMode === ViewerMode.Leaflet) {
return;
}
this.viewerMode = ViewerMode.Leaflet;
} else if (desiredMode === "3d") {
if (fromStory && this.viewerMode === ViewerMode.CesiumTerrain) {
return;
}
this.viewerMode = ViewerMode.CesiumTerrain;
} else if (desiredMode === "3dsmooth") {
if (fromStory && this.viewerMode === ViewerMode.CesiumEllipsoid) {
return;
}
this.viewerMode = ViewerMode.CesiumEllipsoid;
}
}
if (!defined(initSource.timeline) && defined(initSource.currentTime)) {
// If the time is supplied we want to freeze the display at the specified time and not auto playing.
this.autoPlay = false;
const time = initSource.currentTime;
this.clock.currentTime.dayNumber = parseInt(time.dayNumber, 10);
this.clock.currentTime.secondsOfDay = parseInt(time.secondsOfDay, 10);
}
if (defined(initSource.timeline)) {
this.clock.shouldAnimate = initSource.timeline.shouldAnimate;
this.clock.multiplier = initSource.timeline.multiplier;
const time = initSource.timeline.currentTime;
this.clock.currentTime.dayNumber = parseInt(time.dayNumber, 10);
this.clock.currentTime.secondsOfDay = parseInt(time.secondsOfDay, 10);
}
// Populate the list of services.
if (defined(initSource.services)) {
this.services.services.push.apply(this.services, initSource.services);
}
// Populate the catalog
if (defined(initSource.catalog)) {
var isUserSupplied = !initSource.isFromExternalFile;
promise = promise.then(
this.catalog.updateFromJson.bind(this.catalog, initSource.catalog, {
isUserSupplied: isUserSupplied
})
);
}
if (defined(initSource.sharedCatalogMembers)) {
promise = promise.then(
this.catalog.updateByShareKeys.bind(
this.catalog,
initSource.sharedCatalogMembers
)
);
}
if (defined(initSource.locationMarker)) {
var marker = {
name: initSource.locationMarker.name,
location: {
latitude: initSource.locationMarker.latitude,
longitude: initSource.locationMarker.longitude
}
};
addMarker(this, marker);
}
if (defined(initSource.pickedFeatures)) {
promise.then(function() {
var removeViewLoadedListener;
var loadPickedFeatures = function() {
if (defined(removeViewLoadedListener)) {
removeViewLoadedListener();
}
var vectorFeatures;
var featureIndex = {};
var initSourceEntities = initSource.pickedFeatures.entities;
if (initSourceEntities) {
// Build index of terria features by a hash of their properties.
var relevantItems = that.nowViewing.items.filter(function(item) {
return (
item.isEnabled &&
item.isShown &&
defined(item.dataSource) &&
defined(item.dataSource.entities)
);
});
relevantItems.forEach(function(item) {
(item.dataSource.entities.values || []).forEach(function(entity) {
var hash = hashEntity(entity, that.clock);
var feature = Feature.fromEntityCollectionOrEntity(entity);
featureIndex[hash] = featureIndex[hash]
? featureIndex[hash].concat([feature])
: [feature];
});
});
// Go through the features we've got from terria match them up to the id/name info we got from the
// share link, filtering out any without a match.
vectorFeatures = initSourceEntities
.map(function(initSourceEntity) {
var matches = defaultValue(
featureIndex[initSourceEntity.hash],
[]
).filter(function(match) {
return match.name === initSourceEntity.name;
});
return matches.length && matches[0];
})
.filter(function(feature) {
return defined(feature);
});
}
that.currentViewer.pickFromLocation(
initSource.pickedFeatures.pickCoords,
initSource.pickedFeatures.providerCoords,
vectorFeatures
);
that.pickedFeatures.allFeaturesAvailablePromise.then(function() {
that.pickedFeatures.features.forEach(function(entity) {
var hash = hashEntity(entity, that.clock);
var feature = entity;
featureIndex[hash] = featureIndex[hash]
? featureIndex[hash].concat([feature])
: [feature];
});
if (defined(initSource.pickedFeatures.current)) {
var selectedFeatureMatches = defaultValue(
featureIndex[initSource.pickedFeatures.current.hash],
[]
).filter(function(feature) {
return feature.name === initSource.pickedFeatures.current.name;
});
that.selectedFeature =
selectedFeatureMatches.length && selectedFeatureMatches[0];
}
});
};
if (that.currentViewer !== that._noViewer) {
loadPickedFeatures();
} else {
removeViewLoadedListener = that.afterViewerChanged.addEventListener(
loadPickedFeatures
);
}
});
}
return promise;
};
Terria.prototype.getLocalProperty = function(key) {
try {
if (!defined(window.localStorage)) {
return undefined;
}
} catch (e) {
// SecurityError can arise if 3rd party cookies are blocked in Chrome and we're served in an iFrame
return undefined;
}
var v = window.localStorage.getItem(this.appName + "." + key);
if (v === "true") {
return true;
} else if (v === "false") {
return false;
}
return v;
};
Terria.prototype.setLocalProperty = function(key, value) {
try {
if (!defined(window.localStorage)) {
return undefined;
}
} catch (e) {
return undefined;
}
window.localStorage.setItem(this.appName + "." + key, value);
return true;
};
/**
* Returns the side of the splitter the `position` lies on.
*
* @param {(Cartesian2|Cartesian3)} The screen position.
* @return {ImagerySplitDirection} The side of the splitter on which `position` lies.
*/
Terria.prototype.getSplitterSideForScreenPosition = function(position) {
var splitterX =
this.currentViewer.getContainer().clientWidth * this.splitPosition;
if (position.x <= splitterX) {
return ImagerySplitDirection.LEFT;
} else {
return ImagerySplitDirection.RIGHT;
}