-
Notifications
You must be signed in to change notification settings - Fork 0
/
layerviewer.js
5550 lines (4544 loc) · 193 KB
/
layerviewer.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
// LayerViewer library code
/*jslint browser: true, white: true, single: true, for: true, long: true, unordered: true */
/*global $, jQuery, mapboxgl, MapboxDraw, geojsonExtent, autocomplete, Cookies, vex, GeoJSON, FULLTILT, L, Papa, jsSHA, toGeoJSON, alert, console, window, history, DeviceOrientationEvent */
const layerviewer = (function ($) {
'use strict';
// Settings defaults
const _settings = {
// API
apiBaseUrl: 'API_BASE_URL',
apiKey: 'YOUR_API_KEY',
// Mapbox API key
mapboxApiKey: 'YOUR_MAPBOX_API_KEY',
// Initial lat/lon/zoom of map and tile layer
defaultLocation: {
latitude: 54.661,
longitude: 1.263,
zoom: 6
},
maxBounds: null, // Or [W,S,E,N]
defaultTileLayer: 'mapnik',
maxZoom: 20,
// Application baseUrl
baseUrl: '/',
// Default layers ticked
defaultLayers: [],
// Geocoder API URL; re-use of settings values represented as placeholders {%apiBaseUrl}, {%apiKey}, {%autocompleteBbox}, are supported
geocoderApiUrl: '{%apiBaseUrl}/v2/geocoder?key={%apiKey}&bounded=1&bbox={%autocompleteBbox}',
// BBOX for autocomplete results biasing
autocompleteBbox: '-6.6577,49.9370,1.7797,57.6924',
// Feedback API URL; re-use of settings values represented as placeholders {%apiBaseUrl}, {%apiKey}, are supported
feedbackApiUrl: '{%apiBaseUrl}/v2/feedback.add?key={%apiKey}',
// Enable/disable 3D terrain (Mapbox GL JS v.2.0.0+)
enable3dTerrain: false,
// Enable placenames to be above layers
placenamesOnTop: true,
// Enable/disable full screen map control
enableFullScreen: false,
fullScreenPosition: 'top-left',
// Enable/disable drawing feature
enableDrawing: true,
drawingGeometryType: 'Polygon', // Or LineString
// Map scale
enableScale: false,
// First-run welcome message
firstRunMessageHtml: false,
firstRunMessageEmbedMode: true,
// Google API key for Street View images
gmapApiKey: 'YOUR_API_KEY',
// Sending zoom as default for all layers
sendZoom: false,
// Explicit styling as default for all layers
style: {},
// Enable hover for all (line-based) layers
hover: true,
// Zoom control position
zoomPosition: 'bottom-right',
// Geolocation position, or false for no geolocation element
geolocationPosition: 'top-right',
// Geolocation max zoom, to avoid an overly close result
geolocationMaxZoom: 16.5,
// Use existing geolocation button instead of Mapbox's
geolocationElementId: false,
// Determine whether the geolocation tracks the user constantly; set to false for a one-shot control
geolocationTrackUserLocation: false,
// Whether to enable popups
popups: true, // NB Not yet implemented for point-based layers
// Default icon and size
iconUrl: null,
iconSize: null,
// Tileserver URLs, each as [path, options, label]
tileUrls: {
opencyclemap: {
tiles: 'https://{s}.tile.cyclestreets.net/opencyclemap/{z}/{x}/{y}@2x.png',
maxZoom: 22,
attribution: 'Maps © <a href="https://www.thunderforest.com/">Thunderforest</a>, Data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>',
tileSize: 256, // 512 also works but 256 gives better map detail
label: 'OpenCycleMap',
description: 'A cycling-orientated map, highlighting cycle infrastructure, hills, bike shops and more.'
},
mapboxstreets: {
vectorTiles: 'mapbox://styles/mapbox/streets-v11',
label: 'Streets',
description: 'A general-purpose map that emphasizes legible styling of road and transit networks.',
placenamesLayers: ['country-label', 'state-label', 'settlement-label', 'settlement-subdivision-label']
},
light: {
vectorTiles: 'mapbox://styles/mapbox/light-v10',
label: 'Light',
description: 'A light-fade background map.',
placenamesLayers: ['country-label', 'state-label', 'settlement-label', 'settlement-subdivision-label']
},
night: {
vectorTiles: 'mapbox://styles/mapbox/dark-v10',
label: 'Night',
description: 'A subtle, full-featured map designed to provide minimalist geographic context.',
placenamesLayers: ['country-label', 'state-label', 'settlement-label', 'settlement-subdivision-label']
},
satellite: {
vectorTiles: 'mapbox://styles/mapbox/satellite-v9',
label: 'Satellite',
description: "A map that uses real satellite imagery to give you a bird's-eye view of your surroundings."
},
mapnik: {
tiles: 'https://{s}.tile.cyclestreets.net/mapnik/{z}/{x}/{y}.png',
maxZoom: 19,
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
tileSize: 256,
label: 'OpenStreetMap',
description : 'The default OpenStreetMap style, emphasising road type and surrounding buildings.'
},
// See: https://www.ordnancesurvey.co.uk/documents/os-open-zoomstack-vector-tile-api.pdf
// Also later release, requiring a key, at: https://www.ordnancesurvey.co.uk/newsroom/blog/creating-your-own-vector-tiles
osoutdoor: {
vectorTiles: 'https://s3-eu-west-1.amazonaws.com/tiles.os.uk/styles/open-zoomstack-outdoor/style.json',
label: 'OS outdoor',
description: 'Display footpaths, rights of way, open access land and the vegetation on the land.',
placenamesLayers: ['Country names', 'Capital City names', 'City names', 'Town names'],
attribution: 'Contains Ordnance Survey data © Crown copyright and database rights 2018'
},
osopendata: {
tiles: 'https://{s}.tile.cyclestreets.net/osopendata/{z}/{x}/{y}.png',
maxZoom: 19,
attribution: 'Contains Ordnance Survey data © Crown copyright and database right 2010',
tileSize: 256,
label: 'OS Open Data',
description: "The OS's most detailed, street-level mapping product available, using open data sources.",
placenamesLayers: ['Country names', 'Capital City names', 'City names', 'Town names']
},
bartholomew: {
tiles: 'https://{s}.tile.cyclestreets.net/bartholomew/{z}/{x}/{y}@2x.png',
maxZoom: 15,
attribution: '© <a href="https://maps.nls.uk/copyright.html">National Library of Scotland</a>',
tileSize: 256,
label: 'Bartholomew',
description: "John Bartholomew's distinctive 1897 map, using colour to represent landscape relief."
},
os6inch: {
tiles: 'https://{s}.tile.cyclestreets.net/os6inch/{z}/{x}/{y}@2x.png',
maxZoom: 15,
attribution: '© <a href="https://maps.nls.uk/copyright.html">National Library of Scotland</a>',
tileSize: 256,
label: 'OS 6-inch',
description: 'Comprehensive topographic mapping covering all of England and Wales from the 1840s.'
}
/* ,
os1to25k1stseries: {
tiles: 'https://{s}.tile.cyclestreets.net/os1to25k1stseries/{z}/{x}/{y}@2x.png',
maxZoom: 16,
attribution: '© <a href="https://maps.nls.uk/copyright.html">National Library of Scotland</a>',
tileSize: 256,
label: 'NLS - OS 1:25,000 Provisional / First Series 1937-1961',
},
os1inch7thseries: {
tiles: 'https://{s}.tile.cyclestreets.net/os1inch7thseries/{z}/{x}/{y}@2x.png',
maxZoom: 16,
attribution: '© <a href="https://maps.nls.uk/copyright.html">National Library of Scotland</a>',
tileSize: 256,
label: 'NLS - OS 1-inch 7th Series 1955-1961'
}
*/
},
// Popup pages, defined as content div ID
pages: [
// 'about'
],
// Region switcher, with areas defined as a GeoJSON file
regionsFile: false,
regionsField: false,
regionsNameField: false,
regionsSubstitutionToken: false,
regionsPopupFull: false, // Full contents for popup, as per a normal layer
regionSwitcherPosition: 'top-right',
regionSwitcherNullText: 'Move to area',
regionSwitcherCallback: false, // Called when the region switch is detected
regionSwitcherDefaultRegion: false, // Default region to load if no region saved in cookie
regionSwitcherMaxZoom: false,
regionSwitcherPermalinks: false,
// Initial view of all regions; will use regionsFile
initialRegionsView: false,
initialRegionsViewRemovalClick: true, // Whether the regions are removed upon click
initialRegionsViewRemovalZoom: 10, // or false to keep it; 10 is roughly size of a UK County
// Whether to show layer errors in a (non-modal) corner dialog, rather than as a modal popup
errorNonModalDialog: false,
// Beta switch
enableBetaSwitch: false,
// Password protection, as an SHA-256 hash; can also be an array of passwords
password: false,
// Hide default LayerViewer message area and legend
hideExtraMapControls: false,
// Form rescan path
formRescanPath: 'form#data #{layerId}',
// Selector for the form selector
selector: '#selector',
// Custom data loading spinner selector for layerviewer. For layer specific spinner, should contain layerId
dataLoadingSpinnerSelector: '#selector li.{layerId} img.loading',
// Style switcher, either false to create a default Leaflet-style basic switcher, or a selector path for a div that will contain a graphical switcher
styleSwitcherGraphical: false,
// Custom panning control element
panningControlElement: '<p><a id="panning" href="#">Panning: disabled</a></p>',
// Custom panning control element insertion point (will be prepended to this element)
panningControlInsertionElement: '#styleswitcher ul',
// Determine whether to enable layerviewer's text based panning status indication
setPanningIndicator: true,
// Whether to use MapboxGL JS's default navigation controls
useDefaultNavigationControls: true,
// Whether to use MapboxGL JS's default geolocation control
hideDefaultGeolocationControl: false,
// Load Tabs class toggle, used when loading a parameterised URL. This CSS class will be added to the enabled parent li elements (i.e., 'checked', or 'selected')
loadTabsClassToggle: 'selected',
// Use jQuery tabs to tabify main menu
useJqueryTabsRendering: true,
// Rounding decimal places in popups
popupsRoundingDP: 0,
// Clicking "Clear line" also stops the drawing
stopDrawingWhenClearingLine: true,
// Additional layers, e.g. drawn polygons, that should be reset to be on top after layer changes
forceTopLayers: []
};
// Layer definitions, which should be overriden by being supplied as an argument by the calling application
// #!# These do not actually represent defaults, unlike the main config - this should be enabled
let _layerConfig = {
/* Example, showing all available options:
layerid: {
// Path or full URL to the API endpoint
apiCall: '/path/to/api',
// API key specific to this layer's API call
apiKey: false,
// Or fixed data, for GeoJSON layers
data: false,
// Fixed parameters required by this API
apiFixedParameters: {
key: 'value',
foo: 'bar'
},
// Name and description
name: '',
description: '',
// Explicit data type (assumed to be JSON), e.g. XML
dataType: false,
// Callback for data conversion just after receiving the data
convertData: function (data) {return somefunction (data);},
// Whether to fit the data within the map initially upon loading, adjusting the zoom accordingly
fitInitial: false,
fitInitialPadding: false, // Defaults to 20
// Whether to zoom initially upon loading
zoomInitialMin: false,
// Minimum zoom required for this layer
minZoom: false,
// Show a message if the zoom level is below this level (i.e. too zoomed out)
fullZoom: 17,
fullZoomMessage: 'Customised string',
// If the layer requires that query fields are prefixed with a namespace, prefix each fieldname
parameterNamespace: 'field:',
// Whether to send zoom= to the API end, which is useful for some APIs
sendZoom: true,
// Specific icon to use for all markers in this layer
iconUrl: '/images/icon.svg',
// Field in GeoJSON data where the icon value can be looked up
iconField: 'type',
// Icon lookups, based on the iconField
icons: {
foo: '/images/foo.svg',
bar: '/images/bar.svg',
qux: '/images/qux.svg'
},
// Icon size, either fixed or dynamic lookup from a field in the feature properties
iconSize: [38, 42],
iconSizeField: false,
iconSizes: {},
// Order of marker appearance, in order from least to most important
markerImportance: ['foo', 'bar', 'qux'],
// Explicit styling
style: {
weight: 5
},
// If drawing lines, the field that contains the value used to determine the colour, and the colour stops for this, as an array of pairs of upper limit value and colour, or fixed colour
lineColour: false, // Fixed value
lineColourField: 'value',
lineColourStops: [
[200, '#ff0000'],
[50, '#e27474'],
[0, '#61fa61']
],
lineColourValues: {
'foo': '#ff0000',
'bar': '#b2beb5'
},
// Point/Line colour from API response, e.g. 'colour' value in API
pointColourApiField: false,
lineColourApiField: false,
// Point size
pointSize: 8,
// Line width
lineWidth: false, // Fixed value
lineWidthField: 'width',
lineWidthStops: [
[250, 10],
[100, 5],
[0, 1],
],
lineWidthValues: {
'foo': 5,
'bar': 2
},
// Enable hover for this layer (for line-based layers)
hover: true,
// Legend, either array of values (as same format as polygonColourStops/lineColourStops), or boolean true to use polygonColourStops/lineColourStops if either exists (in that order of precedence)
legend: true,
// Polygon style; currently supported values are 'grid' (blue boxes with dashed lines, intended for tessellating data), 'green', 'red', 'blue'
polygonStyle: 'grid',
polygonColourField: false,
polygonColourStops: [
[200, '#ff0000'],
[50, '#e27474'],
[0, '#61fa61']
],
polygonColourValues: {
'foo': '#ff0',
'bar': '#b2beb5'
},
fillOpacity: 0.6,
fillOutlineColor: 'rgba(0, 0, 0, 0.2)',
// A secondary API call, used to get a specific ID
apiCallId: {
apiCall: '/path/to/secondaryApi',
idParameter: 'id',
apiFixedParameters: {
key: 'value',
foo: 'bar'
},
popupAnimation: 'true',
},
// Code for popups; placeholders can be used to reference data in the GeoJSON; if using sublayerParameter, this is specified as a hashmap
popups: true, // NB Not yet implemented for point-based layers
popupHtml:
+ '<p>Reference: <strong>{properties.id}</strong></p>'
+ '<p>Date and time: {properties.datetime}</p>',
// Formatter for popup fields when using auto-table creation
popupImagesField: false,
popupFormatters: {
myField: function (value, feature) {return string;},
...
},
// Layer-specific feedback buttons
popupFeedbackButton: false, // or string containing button text
locateFeedbackButton: false, // or string containing button text
// Rounding decimal places in popups
popupsRoundingDP: 0,
// Whether to enable Street View in popups (for auto-popups)
streetview: true,
// Make lookups (Popups / line colour stops) dependent on the value of a specified request parameter
// Currently supported for: lineColourField, lineColourStops, lineWidthField, lineWidthStops, polygonColourField, polygonColourValues, popupHtml, legend
// #!# This is currently a poor architecture; each supported config type has to be enabled deep in the execution tree, whereas this should be done as a single generic hit near the start of getData ()
sublayerParameter: false,
// Replace auto-generated keys in popup with pretty titles or descriptions
fieldLabelsCsv: false,
fieldLabelsCsvField: 'field',
fieldLabelsCsvTitle: 'title',
fieldLabelsCsvDescription: 'description',
// Labels and descriptions for auto-popups
popupLabels: {},
popupDescriptions: {},
// Field that contains a follow-on API URL where more details of the feature can be requested
detailsOverlay: 'apiUrl',
// Overlay code, as per popupHtml, but for the follow-on overlay data
overlayHtml: '<p>{properties.caption}</p>',
// Optimisation flag to state that the data is static, i.e. no change based on map location
static: false,
// Retrieval strategy - 'bbox' (default) sends w,s,e,n; 'polygon' sends as sw.lat,sw.lng:se.lat,se.lng:ne.lat,ne.lng:nw.lat,nw.lng:sw.lat,sw.lng, 'none' sends neither (i.e. static)
retrievalStrategy: 'bbox',
// Boundary parameter name (most likely to be useful in polygon retrievalStrategy mode), defaulting to 'boundary'
apiBoundaryField: 'boundary',
// If reformatting the boundary in the response is needed, unpacking strategy; only 'latlon-comma-colons' is supported
apiBoundaryFormat: 'latlon-comma-colons',
// Flat JSON mode, for when GeoJSON is not available, specifying the location of the location fields within a flat structure
flatJson: ['location.latitude', 'location.longitude'],
// Heatmap mode
heatmap: false,
// Tile layer mode, which adds a bitmap tile overlay
tileLayer: [], // Format as per _settings.tileUrls
// Marker-setting mode, which requires a hidden input field; a default value of that field will set an initial location; uses iconUrl
setMarker: false
},
*/
};
// Define the supported OpenGIS types; this registry is currently only used for popups
const _opengisTypes = [
'Point',
'LineString',
'Polygon'
];
// Define the geometry types and their default styles
const _defaultStyles = {
'Point': {
// NB Icons, if present, are also drawn over the points
type: 'circle',
layout: {}, // Not applicable
paint: {
'circle-radius': 8,
'circle-color': '#007cbf'
}
},
'LineString': {
type: 'line',
layout: {
'line-cap': 'round',
'line-join': 'round'
},
paint: {
'line-color': ['case', ['has', 'color'], ['get', 'color'], /* fallback: */ '#888'],
'line-width': 3
}
},
'Polygon': {
type: 'fill',
layout: {}, // Not applicable
paint: {
'fill-color': '#888',
'fill-opacity': 0.4,
'fill-outline-color': 'rgba(0,0,0,0.5)' // See: https://github.com/mapbox/mapbox-gl-js/issues/3018#issuecomment-365767174
}
}
};
// Internal class properties
let _map = null;
const _layers = {}; // Layer status registry
const _backgroundMapStyles = {};
const _backgroundMapStylesManualAttributions = {};
let _manualAttribution = null;
let _currentBackgroundMapStyleId;
const _backgroundStylesInternalPrefix = 'background-';
const _markers = [];
const _popups = [];
let _tileOverlayLayer = false;
let _isTouchDevice;
let _panningEnabled = false;
const _virginFormState = {};
const _parameters = {};
const _dataRefreshHandlers = {};
const _xhrRequests = {};
const _requestCache = {};
const _sublayerValues = {};
const _fitInitial = {};
let _title = false;
let _embedMode = false;
let _betaMode = false;
const _message = {};
const _regionBounds = {};
let _regionSwitcherDefaultRegionFromUrl = false;
let _selectedRegion = false;
let _locateHandlerFunction;
let _locateHandlerMarker;
const _miniMaps = {}; // Handle to each mini map
const _miniMapLayers = {}; // Handle to each mini map's layer
let _geolocate = null; // Store the geolocation element
let _geolocationAvailable = false; // Store geolocation availability, to automatically disable location tracking if user has not selected the right permissions
let _customPanningIndicatorAction = false; // Custom function that can be run on click action panning on and off, i.e. to control the visual state of a custom panning button
let _customGeolocationButtonAction = false; // Custom function that can be run on click event on geolocation control, i.e. to control the visual state of a custom geolocation control
let _drawing = {} // Object to control drawing, accessible externally to LayerViewer via registering a listener; structure defined in drawing () function
let _draw = null; // Store the Mapbox draw object
let _popupClickHandlers = {};
return {
// Public functions
// Main function
initialise: function (config, layerConfig)
{
// Merge the configuration into the settings
$.each (_settings, function (setting, value) {
if (config.hasOwnProperty(setting)) {
_settings[setting] = config[setting];
}
});
// Determine if the device is a touch device
_isTouchDevice = layerviewer.isTouchDevice ();
// Enable general page handlers
if (_settings.pages) {
$.each (_settings.pages, function (index, contentDivId) {
layerviewer.pageDialog (contentDivId);
});
}
// Require password if enabled
if (_settings.password) {
if (!layerviewer.passwordProtection ()) {
return false;
}
}
// Obtain the layers
_layerConfig = layerConfig;
// Parse the URL
const urlParameters = layerviewer.parseUrl ();
// Set the initial location and tile layer
const defaultLocation = (urlParameters.defaultLocation || _settings.defaultLocation);
const defaultTileLayer = (urlParameters.defaultTileLayer || _settings.defaultTileLayer);
// Load background map style defitions
layerviewer.getBackgroundMapStyles ();
// Create the map
layerviewer.createMap (defaultLocation, defaultTileLayer);
// Hide unwanted UI elements in embed mode if required
layerviewer.embedMode ();
// If HTML5 History state is provided, use that to select the sections
let initialLayersPopstate = false;
/* Doesn't work yet, as is asyncronous - need to restructure the initialisation
$(window).on('popstate', function (e) {
const popstate = e.originalEvent.state;
if (popstate !== null) {
initialLayersPopstate = popstate;
}
});
*/
// If cookie state is provided, use that to select the sections
const initialLayersCookies = [];
let state = Cookies.get ('state');
if (state) {
state = JSON.parse (state);
$.each (state, function (layerId, parameters) {
if (_layerConfig[layerId]) {
initialLayersCookies.push (layerId);
}
});
}
// Determine layers to use, checking for data in order of precedence
const initialLayers = initialLayersPopstate || (urlParameters.sections.length ? urlParameters.sections : false) || (initialLayersCookies.length ? initialLayersCookies : false) || _settings.defaultLayers;
// Load the tabs
layerviewer.loadTabs (initialLayers);
// Create mobile navigation
layerviewer.createMobileNavigation ();
// Populate dynamic form controls
layerviewer.populateDynamicFormControls ();
// Add slider value display support
layerviewer.sliderValueDisplayHandler ();
// Determine the enabled layers
layerviewer.determineLayerStatus ();
// Determine the initial form state as specified in the fixed HTML, irrespective of URL-supplied values, for all layers
$.each (_layers, function (layerId, layerEnabled) {
_virginFormState[layerId] = layerviewer.parseFormValues (layerId);
});
// Set form values specified in the URL
layerviewer.setFormValues (urlParameters.formParameters);
// Add tooltip support
layerviewer.tooltips ();
// Set dialog style
vex.defaultOptions.className = 'vex-theme-plain';
// Register a more details dialog box handler, giving a link to more information
layerviewer.moreDetails ();
// Show first-run welcome message if the user is new to the site
layerviewer.welcomeFirstRun ();
// Create the legend for the current field, and update on changes
layerviewer.createLegend ();
// Create a beta switch if required
layerviewer.createBetaSwitch ();
// Create a message area, and provide methods to manipulate it
layerviewer.messageArea ();
// Region switcher
layerviewer.regionSwitcher ();
// Show intial regions view if required
layerviewer.initialRegionsView (urlParameters);
// Enable feedback handler
layerviewer.feedbackHandler ();
// Populate each layer with popupLabels if fieldLabelsCsv is provided
$.each (_layers, function (layerId, layerEnable) {
layerviewer.populateFieldLabels (layerId);
});
// Load the data, and add map interactions and form interactions
_map.on ('load', function () { // Because layers may do addLayer(), the whole layer management must be wrapped in map load; see: https://docs.mapbox.com/help/how-mapbox-works/web-apps/#adding-layers-to-the-map
$.each (_layers, function (layerId, layerEnabled) {
if (layerEnabled) {
layerviewer.enableLayer (layerId);
}
});
});
// On style (background map) change, reload layers
// This area of Mapbox GL JS is highly buggy; see: https://github.com/mapbox/mapbox-gl-js/issues/8691
$('body').on ('style-changed', function (event) {
$.each (_layers, function (layerId, layerEnabled) {
if (layerEnabled) {
// Remove the layer
layerviewer.removeLayer (layerId);
// After a short delay, re-enable the layer; it seems removeLayer takes some time to unload, so the delay is essential as otherwise layers will not re-appear
setTimeout (function () {
layerviewer.enableLayer (layerId);
}, 200);
// #!# NB Drawing layer may disappear
}
});
});
// If an ID is supplied in the URL, load it
layerviewer.loadIdFromUrl (urlParameters);
// Toggle map data layers on/off when checkboxes changed
$(_settings.selector + ' input[type="checkbox"]').change (function(event) {
layerviewer.toggleDataLayer (event.target);
});
// Enable embed dialog handler
layerviewer.embedHandler ();
},
// Function to set a layer configuration after loading
setLayerConfigParameter: function (layer, field, value)
{
_layerConfig[layer][field] = value;
},
// Function to toggle map data layers on/off when checkboxes changed
toggleDataLayer: function (target)
{
// Add class to facilitate display of an icon
const layerId = target.id.replace('show_', '');
if (target.checked) {
_layers[layerId] = true;
layerviewer.enableLayer (layerId);
} else {
_layers[layerId] = false;
if (_xhrRequests[layerId]) {
_xhrRequests[layerId].abort();
}
layerviewer.removeLayer (layerId);
layerviewer.clearLegend ();
}
},
// Getter for map
getMap: function ()
{
return _map;
},
// Getter for _drawingHappening object
getDrawingStatusObject: function ()
{
return _drawing;
},
// Getter for _draw object
getDrawObject: function ()
{
return _draw;
},
// Function to determine if the device is a touch device
isTouchDevice: function ()
{
// See https://stackoverflow.com/a/13470899/180733
return 'ontouchstart' in window || navigator.msMaxTouchPoints; // https://stackoverflow.com/a/13470899/180733
},
// Password protection; this is intended to provide a simple, basic level of protection only
passwordProtection: function ()
{
// Obtain the cookie if present
const hostSuffix = window.location.hostname.toLowerCase().replace(/[^a-z]+/g, '');
const cookieName = 'login' + hostSuffix;
const value = Cookies.get (cookieName);
// Validate if value supplied from cookie
if (value) {
if (layerviewer.validatePassword (value)) {
return true;
}
}
// Get the home page HTML and overwrite the content
let html = $('#home').html ();
html = '<div id="protection">' + html + '</div>';
$('main').html (html);
// Add a password form
$('#protection').append ('<p id="loginprompt">If you have been given a login password, please enter it below.</p>');
const form = $('<form id="password" method="post"></form>');
form.append('<input name="password" type="password" required="required" placeholder="Password" size="20" autofocus="autofocus" />');
form.append('<input type="submit" value="Submit" />');
$('#protection').append (form);
// If the form is submitted, validate the value
$('#password').submit (function(event) {
// Prevent page reload
event.preventDefault();
// Obtain the value and validate the password
const values = $(this).serializeArray ();
const password = values[0].value;
if (layerviewer.validatePassword (password)) {
// Set the cookie, storing the (low-security) entered value
Cookies.set(cookieName, password, {expires: 7});
// Reload the page and end
location.reload ();
} else {
// Show message
vex.dialog.alert ({
message: 'The password you gave is not correct. Please check and try again.',
showCloseButton: true,
className: 'vex vex-theme-plain',
afterClose: function () {
$('form#password')[0].reset(); // See: https://stackoverflow.com/a/21514788/180733
$('form#password input[type="password"]').focus();
}
});
}
});
// Not validated
return false;
},
// Helper function to validate the password
validatePassword: function (value)
{
// Hash the value
const shaObj = new jsSHA ('SHA-256', 'TEXT');
shaObj.update (value);
const hash = shaObj.getHash ('HEX');
// If a string, convert to array
if (typeof _settings.password == 'string') {
_settings.password = [_settings.password];
}
// Compare against the correct password hash
let matched = false;
$.each (_settings.password, function (index, password) {
if (hash === password) {
matched = true;
return false; // break
}
});
// Failure
return matched;
},
// Function to parse the URL
parseUrl: function ()
{
// Start a list of parameters
const urlParameters = {};
// Split the path by slash; see: https://stackoverflow.com/a/8086637
let url = window.location.pathname;
url = url.substring (_settings.baseUrl.length); // Remove baseUrl from start
const pathComponents = url.split ('/');
if (pathComponents) {
if (_settings.regionSwitcherPermalinks) {
_regionSwitcherDefaultRegionFromUrl = pathComponents[0];
pathComponents.splice (0, 1); // Shift from start, so that the indexes below work as normal
}
// Obtain the sections and form parameters from the URL
const formParameters = layerviewer.urlSlugToFormParameters (pathComponents[0]);
// Obtain the section(s), checking against the available sections in the settings
urlParameters.sections = [];
if (formParameters) {
$.each (formParameters, function (layerId, parameters) {
if (_layerConfig[layerId]) {
urlParameters.sections.push (layerId);
}
});
}
// Register the form parameters
urlParameters.formParameters = formParameters;
// Register non-form components (i.e., Photomap popup)
if (pathComponents[1]) {
urlParameters.id = pathComponents[1];
}
// Obtain embed mode if present
// #¡# Needs to recognise whether embed is the last (but not the first) parameter
if (pathComponents[1]) {
if (pathComponents[1] == 'embed') {
_embedMode = true;
}
}
}
// Obtain query string parameters, which are used for presetting form values
urlParameters.queryString = layerviewer.parseQueryString ();
// Get the location from the URL
urlParameters.defaultLocation = null;
urlParameters.defaultTileLayer = null;
if (window.location.hash) {
const hashParts = window.location.hash.match (/^#([0-9]{1,2}.?[0-9]*)\/([-.0-9]+)\/([-.0-9]+)\/([a-z0-9]+)$/); // E.g. #17.21/51.51137/-0.10498/opencyclemap
if (hashParts) {
urlParameters.defaultLocation = {
latitude: hashParts[2],
longitude: hashParts[3],
zoom: hashParts[1]
};
urlParameters.defaultTileLayer = hashParts[4];
// Remove the tile layer element, before loading the map, so that the MapboxGL hash value is as expected
window.location.hash = window.location.hash.replace ('/' + urlParameters.defaultTileLayer, '');
}
}
// Return the parameters
return urlParameters;
},
// Function to parse the query string into key/value pairs
parseQueryString: function ()
{
// See: https://stackoverflow.com/a/8649003/180733
if (!location.search.length) {return {};}
const queryString = location.search.substring(1);
const parameters = layerviewer.deparam (queryString);
return parameters;
},
// Function to add an initial regions view
initialRegionsView: function (urlParameters)
{
if (_settings.initialRegionsView && _settings.regionsFile) {
if (!urlParameters.defaultLocation) {
// Add the data, rendering the polygons
_map.on ('load', function () { // See: https://docs.mapbox.com/help/how-mapbox-works/web-apps/#adding-layers-to-the-map
_map.addLayer ({
id: 'regionsOverlay',
source: {
type: 'geojson',
data: _settings.regionsFile,
generateId: true // NB See: https://github.com/mapbox/mapbox-gl-js/issues/8133
},
type: 'fill',
layout: {},
paint: {
'fill-color': '#3388ff',
'fill-opacity': ['case', ['boolean', ['feature-state', 'hover'], false], 1, 0.5], // See: https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/
'fill-outline-color': 'blue'
// NB Outline line width cannot be changed: https://github.com/mapbox/mapbox-gl-js/issues/3018#issuecomment-240381965
}
});
});
// Set hover state; see: https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/
layerviewer.hoverStateHandlers ('regionsOverlay', 'regionsOverlay');
// Support popup content, if enabled
if (_settings.regionsField) {