-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
913 lines (760 loc) · 54.3 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta charset="UTF-8"/>
<meta name="keywords" content="explore, map, mapping, interactive, spatial, trafford, leaflet, leafletjs, geojson, data"/>
<meta name="description" content="Explore the different assets, facilities and areas within the borough of Trafford."/>
<title>Trafford Data Lab: Explore</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin=""/>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/MarkerCluster.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/MarkerCluster.TraffordDataLab.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans%7CRoboto"/>
<link rel="stylesheet" href="https://www.trafforddatalab.io/css/labBase.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/labLeafletMap.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/leaflet.reachability.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/leaflet.reachability_lab.min.css"/>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css"/>
<style>
.aboutContainer
{
margin-bottom: 10px;
}
.infoDockContainer
{
max-height: 250px;
}
.propertiesTable
{
width: 100%;
font-size: 12px;
background-color: rgba(240,240,240,0.5);
}
.propertiesTable td
{
vertical-align: top;
border-bottom: 1px dotted #ccc;
}
.propertiesTable td:nth-child(1)
{
font-weight: bold;
width: 1%;
white-space: nowrap;
}
.datasetSelect
{
width: 100%;
}
@media (min-width:621px)
{
.mainPanelControl
{
width: 280px; /* desired width when not on mobiles */
}
}
.toggleCluster
{
font-size: 12px;
}
.shareButton
{
padding-right: 9px;
}
.shareButtonActive
{
color: #fc6721;
}
</style>
</head>
<body>
<div id="map" class="mapFullScreen">
<input type="text" id="shareUrl" contenteditable="true" readonly="false" style="width: 1px; height: 1px; border: 0; left: -333px; top: -333px;"/>
</div>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/L.Control.Locate.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/leaflet.markercluster.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/mapbox-gl-leaflet@error_handler/leaflet-mapbox-gl.min.js"></script>
<script src="https://www.trafforddatalab.io/assets/javascript/labError.js"></script>
<script src="https://www.trafforddatalab.io/assets/javascript/labAjax.js"></script>
<script src="https://www.trafforddatalab.io/assets/javascript/labGetQryStrValByKey.js"></script>
<script src="https://www.trafforddatalab.io/assets/javascript/labSpinner.js"></script>
<script src="https://www.trafforddatalab.io/assets/javascript/changeLuminosity.js"></script>
<script src="https://www.trafforddatalab.io/assets/javascript/supportWebGL.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/labMarkerSVG.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/labCreateTileLayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/labCreateVectorTileLayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/labLeafletMap.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/leaflet.reachability_lab_setup.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/trafforddatalab/[email protected]/leaflet.reachability.min.js"></script>
<script>
// 2019-07-11: For compatibility with URLs containing a QueryString to specify a dataset, (e.g. https://www.trafforddatalab.io/explore/?dataset=libraries) the following replaces it for a hash causing the page to reload.
// In most circumstances this should go unnoticed. The new method uses hashes to record map state as this allows the url to be updated without reloading the page.
if (location.href.indexOf('?') > -1) location.href = location.href.replace('?', '#');
// ######### FUNCTIONS #########
// To setup each feature within GeoJSON
function featureEvents (feature, layer) {
// we need to discover the feature type - remember it is valid for this to be null!
if (feature.hasOwnProperty('type')) {
featureType = feature.type.toLowerCase();
if (featureType == 'feature' || featureType == 'featurecollection') {
if (feature.hasOwnProperty('geometry') && feature.geometry.hasOwnProperty('type')) featureType = (feature.geometry.type !== null) ? feature.geometry.type.toLowerCase() : null;
}
}
// based on the feature type we now need to set the correct layer type
if (featureType == 'point' && feature.hasOwnProperty('properties') && feature.properties.hasOwnProperty('featureRadius') && feature.properties.featureRadius !== '') {
layer.type = 'circle'; // special case as there is no circle in GeoJSON - therefore we can only distinguish between a circle and a point if we have a radius value
}
else if (featureType == 'point' || featureType == 'multipoint') {
layer.type = 'marker';
// For this type of layer we also want to store the colour and the size of the marker
// If the information is not present use defaults of medium and Lab orange
layer.markerColour = (feature.hasOwnProperty('properties') && feature.properties.hasOwnProperty('marker-color')) ? feature.properties['marker-color'] : '#fc6721';
layer.markerSize = (feature.hasOwnProperty('properties') && feature.properties.hasOwnProperty('marker-size')) ? feature.properties['marker-size'] : 'medium';
}
else if (featureType == 'polygon' || featureType == 'multipolygon') {
layer.type = 'polygon';
}
else if (featureType == 'linestring' || featureType == 'multilinestring') {
layer.type = 'polyline';
}
else {
layer.type = featureType; // probably null
}
// Add handler to layer to show properties onclick
layer.on({
click: showLayerProps
});
}
// This function is for styling non-point data. If it has internal styling properties use them, otherwise use a default
function styleOverlayData(feature) {
var styles = {
color: '#fc6721',
fillColor: '#fc6721',
opacity: 0.5,
fillOpacity: 0.2
};
var props = feature.properties;
if (props != null) {
if (props['stroke'] != null) styles['color'] = props['stroke'];
if (props['stroke-width'] != null) styles['weight'] = props['stroke-width'];
if (props['stroke-opacity'] != null) styles['opacity'] = props['stroke-opacity'];
if (props['fill'] != null) styles['fillColor'] = props['fill'];
if (props['fill-opacity'] != null) styles['fillOpacity'] = props['fill-opacity'];
}
return styles;
}
// To setup any point data features within GeoJSON
function pointData (feature, latlng) {
if (labMap.datasetCluster == null) {
// create the marker cluster object in case we require this feature - also indicates to the application that we have point data in the dataset
labMap.datasetCluster = L.markerClusterGroup({
spiderLegPolylineOptions: { weight: 2, color: '#fc6721', opacity: 0.5 },
polygonOptions: { weight: 2, color: '#fc6721', opacity: 0.5, dashArray: '5' }
});
}
if (feature.hasOwnProperty('properties') && feature.properties.hasOwnProperty('featureRadius') && feature.properties.featureRadius !== '') {
// create a circle marker as we have a radius property value
return L.circle(latlng, { radius: feature.properties.featureRadius });
}
else {
// get the colour and size information if available from the properties object, otherwise use defaults
var markerColour = (feature.hasOwnProperty('properties') && feature.properties.hasOwnProperty('marker-color')) ? feature.properties['marker-color'] : '#fc6721';
var markerSize = (feature.hasOwnProperty('properties') && feature.properties.hasOwnProperty('marker-size')) ? feature.properties['marker-size'] : 'medium';
return L.marker(latlng, { icon: labMarkerSVG({
color: markerColour,
size: markerSize
})
});
}
}
// Reset the styling of a previously selected feature
function resetFeatureStyle() {
if (labMap.featureCache != null) {
var layer = labMap.featureCache;
if (layer.type == 'marker') {
// Specific reset implementation for markers
layer.setIcon(labMarkerSVG({
color: layer.markerColour,
size: layer.markerSize
})
);
}
else if (isDatasetLayer(layer)) {
// The feature belongs to a dataset that has been loaded
labMap.datasetGeoJson.resetStyle(layer);
}
else if (isIsolineLayer(layer)) {
// The feature is an isoline drawn with the reachability plugin
labMap.reachabilityControl.isolinesGroup.resetStyle(layer);
}
else {
// The feature is a polygon from a geography boundary. Easier to just set the style back to the default than resetting it via the L.geoJSON method
layer.setStyle(labMap.poly);
}
labMap.featureCache = null; // clear the cache to prevent a situation where no feature is currently selected but the cache still contains the previously selected layer
}
}
// Show the properties of a selected layer
function showLayerProps(e) {
L.DomEvent.stopPropagation(e); // stop the event bubbling to the map which would cause the information to be removed from the info panel etc.
var layer = e.target;
var propsTable = '';
// Find out what type of layer this is
var isReachability = isIsolineLayer(layer);
var isGeography = isGeographyLayer(layer);
var isDataset = isDatasetLayer(layer);
// reset the style of a previously selected feature
resetFeatureStyle();
// add new selected feature to the cache
labMap.featureCache = layer;
// set the highlight style of the selected feature
if (layer.type == 'marker') {
layer.setIcon(labMarkerSVG({
color: '#ffea00',
size: layer.markerSize
})
);
}
else {
layer.setStyle(labMap.polySelected);
/*
Do we want to bring this layer to the front? If it's a boundary geography definitely yes as they often have overlapping lines. When we select one, we want the whole outline to be on top as it is highlighted in yellow, not have parts hidden under the black lines of neighbouring boundaries. The same is true for certain datasets like the Agricultural land. However, with reachability isolines, the user wouldn't be able to select the smaller intervals once they'd selected a larger one if the layers reordered, as the larger one would be covering the smaller layer(s). The same is also true for certain other layered datasets like OS Greenspaces which have smaller polygons layered on top of larger ones and the ordering needs to be preserved.
So, how to handle this? Only bring the layer to the front if belongs to a geography layer, or if it belongs to a dataset and there isn't a flag in the datasets.json telling us not to.
*/
if (isGeography || (isDataset && labMap.preventLayerToFront == false)) layer.bringToFront();
}
// build the content for the properties table to be displayed
if (layer.feature.hasOwnProperty('properties')) {
var props = layer.feature.properties;
var propsVal, prefix;
var matchIndex = 0;
var arrEmail = [];
for (var key in props) {
// Ensure that the key is a valid property of the GeoJson object and isn't one of the styling options or a reachability range/area units or measure attribute (because we deal with these later)
if (props.hasOwnProperty(key) && key != 'stroke' && key != 'stroke-width' && key != 'stroke-opacity' && key != 'fill' && key != 'fill-opacity' && key != 'marker-color' && key != 'marker-size' && !(isReachability && (key.indexOf('units') > -1 || key == 'Measure'))) {
if (props[key] === null || props[key] === undefined || props[key] !== props[key]) { // The strange test of the property value not equalling itself is for NaN as NaN, uniquely, is never equal to itself
propsVal = '';
}
else if (isNaN(props[key])) { // Given that we have screened out the possibility of props[key] being NaN, this test is to check if props[key] is numeric or not. If it's not just numeric we might want to perform some processing on it to enhance the presentation.
/*
To enhance usability turn email or web addresses found within the property value into hyperlinks. Works for single or multiple occurrences
NOTE:
- For efficiency this is done here each time the user selects a feature, rather than on the whole dataset when it is loaded. It is likely only a few features will be selected by the user.
- Not claiming to match every occurrence, but a high proportion. There will always be ones that slip through, but this is an enhancement feature rather than a validation so isn't an issue.
- The method of pushing the matching email addresses to an array, substituting an indexed string then replacing with the HTML link is done to prevent the second regex matching the domain parts of email addresses or parts of the href property etc.
- Regex obtained from: https://emailregex.com and http://urlregex.com
*/
// Find email addresses
propsVal = props[key].replace(/[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/gi, function (x) {
arrEmail.push('<a href="mailto:' + x + '">' + x + '</a>');
return '@@@EMAIL' + matchIndex++ + '@@@'; // replace with a temporary placeholder to prevent the web address regex matching part of the email addresses as well
});
// Find URLs - NOTE: we need to replace the value of propsVal NOT props[key] as we might have properties with a mix of email and web addresses
propsVal = propsVal.replace(/\b(<a href=")?(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\b/gi, function (x) {
var prefix = (x.indexOf('http://') > -1 || x.indexOf('https://') > -1) ? '' : 'http://'; // if the URL doesn't contain the protocol we'll assume http://
return '<a href="' + prefix + x + '" target="_blank">' + x + '</a>';
});
// Finally replace all email addresses found
for (var i = 0; i < arrEmail.length; i++) {
propsVal = propsVal.replace('@@@EMAIL' + i + '@@@', arrEmail[i]);
}
}
else {
// Value seems to be a number
propsVal = props[key]; // set to the raw value initially
// The following are only applicable if the selected object is a reachability polygon
if (isReachability) {
switch (key) {
case 'Range':
propsVal = '0 - ' + props['Range'] + ' ' + props['Range units']; // Improves the presentation of the range information
break;
case 'Area':
propsVal = props['Area'] + ' ' + props['Area units'].replace('^2', '<sup>2</sup>'); // Improves the presentation of the area information
break;
case 'Latitude':
case 'Longitude':
propsVal = props[key].toFixed(4); // Reduce the precision of the lat/lng values to a sensible number
break
case 'Population':
propsVal = props[key].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // Format the population number with commas separating thousands
}
}
}
propsTable += '<tr><td>' + formatPropertyKey(key) + '</td><td>' + propsVal + '</td></tr>'; // Create a row for the property table to display the key and value
}
}
if (propsTable != '') labMap.updateInfo('<table class="propertiesTable">' + propsTable + '</table>'); // So long as we have something to display, show the completed property table
}
}
// for loading data as an overlay layer
function loadDatasetLayer(datasetKey, resetClusterQS) {
if (resetClusterQS) updateMapStateUrl('cluster', null); // remove the cluster key from the URL hash if desired - e.g. when loading the dataset from the select list we want the decision as to whether point data is clustered or not by default to be made based on the cluster flag value in datasets.json, not from the QS
// Remove any current data layer and reset the variables
if (labMap.datasetLayer !== null) {
labMap.datasetLayer.removeFrom(labMap.map);
labMap.attribution.removeAttribution(labMap.datasetGeoJson.getAttribution()); // have to remove the attribution manually due to a seeming bug in Leaflet.MarkerCluster not handling it automatically
labMap.datasetLayer = null;
labMap.datasetGeoJson = null;
labMap.datasetCluster = null;
labMap.preventLayerToFront = false; // Default behaviour for dataset layers is to bring them to the front when selected. To prevent this happening the dataset needs to have a key 'preventLayerToFront' set to true in datasets.json
// ensure the cluster checkbox is hidden
if (L.DomUtil.hasClass(labMap.toggleClusterContainer, 'hideContent') == false) L.DomUtil.addClass(labMap.toggleClusterContainer, 'hideContent');
// reset the info panel if a feature from the previous dataset was selected
if (labMap.featureCache != null && isGeographyLayer(labMap.featureCache) == false && isIsolineLayer(labMap.featureCache) == false) {
labMap.updateInfo();
labMap.featureCache = null;
}
// reset the legend panel
labMap.updateLegend();
}
// Check to see if the dataset key we've been given matches any datset objects
if (labMap.objDatasets.hasOwnProperty(datasetKey)) {
// Set the page title to match the dataset title.
document.title = 'Trafford Data Lab: ' + labMap.objDatasets[datasetKey].title;
// Update the about section
labMap.updateAbout(labMap.objDatasets[datasetKey].about);
startLabSpinner() // inform the user that something is loading
// Attempt to load GeoJSON specified in the URL
labAjax(labMap.objDatasets[datasetKey].url, function (data) {
if (data !== null && data !== '') {
try {
// set the options for the GeoJSON layer
var layerOptions = { style: styleOverlayData, onEachFeature: featureEvents, pointToLayer: pointData, pane: 'pane_data_overlay' };
if (labMap.objDatasets[datasetKey].attribution !== null) layerOptions['attribution'] = 'Data source: ' + labMap.objDatasets[datasetKey].attribution;
labMap.datasetGeoJson = L.geoJSON(data, layerOptions); // create and store the GeoJSON object
// do we have point data in the dataset?
if (labMap.datasetCluster != null) {
labMap.datasetCluster.addLayer(labMap.datasetGeoJson); // add the GeoJSON to the cluster object - point data will be clustered but polygons/lines won't
// the following is a patch for a seeming bug in Leaflet.MarkerCluster not handling the layer attribution automatically
if (labMap.objDatasets[datasetKey].attribution !== null) labMap.attribution.addAttribution('Data source: ' + labMap.objDatasets[datasetKey].attribution);
// do we want clustering on or off?
// order of precedence: 1. cluster and preventUncluster flags in datasets.json are both TRUE, 2. cluster QS value is TRUE (if loading the dataset via URL, not the select list), 3. cluster flag in datasets.json is TRUE
// preventUncluster flag is for datasets containing huge numbers of points that would crash the browser, this disables the cluster checkbox to prevent the user unclustering
var clusterFlagSet = (labMap.objDatasets[datasetKey].hasOwnProperty('cluster') && labMap.objDatasets[datasetKey].cluster === true) ? true : false;
var preventUnclusterFlagSet = (labMap.objDatasets[datasetKey].hasOwnProperty('preventUncluster') && labMap.objDatasets[datasetKey].preventUncluster === true) ? true : false;
var clusterQS = labGetQryStrValByKey('cluster', location.hash); // check if we're trying to set clustering via the querystring
if ((clusterFlagSet && preventUnclusterFlagSet) || clusterQS === 'true' || (clusterQS !== 'false' && clusterFlagSet)) {
labMap.datasetLayer = labMap.datasetCluster; // the layer we are going to add to the map is the clustered version
labMap.toggleCluster.checked = true;
}
else {
labMap.datasetLayer = labMap.datasetGeoJson; // the layer we are going to add to the map is the straight GeoJSON we loaded
labMap.toggleCluster.checked = false;
}
// now determine if we need to prevent the user from unclustering the dataset
if (clusterFlagSet && preventUnclusterFlagSet) {
labMap.toggleCluster.setAttribute("disabled", "disabled");
}
else {
labMap.toggleCluster.removeAttribute("disabled");
}
L.DomUtil.removeClass(labMap.toggleClusterContainer, 'hideContent'); // show the clustering checkbox
}
else {
labMap.datasetLayer = labMap.datasetGeoJson; // the layer we are going to add to the map is the straight GeoJSON we loaded
updateMapStateUrl('cluster', null); // ensure there is no cluster key in the URL hash
}
// add the dataset layer to the map
labMap.datasetLayer.addTo(labMap.map);
// add legend content if applicable
if (labMap.objDatasets[datasetKey].hasOwnProperty('legend') && labMap.objDatasets[datasetKey].legend != null && labMap.objDatasets[datasetKey].legend !== '') labMap.updateLegend(labMap.objDatasets[datasetKey].legend);
// update the URL with the dataset selected
updateMapStateUrl('dataset', datasetKey);
/*
Check if we want to prevent the layers within the dataset being brought to the front when selected (default is false).
Some datasets like OS Greenspaces have smaller objects overlaid on larger ones, so bringing layers to the front disrupts this and causes issues for the user (e.g. smaller objects can become unselectable behind larger ones).
*/
if (labMap.objDatasets[datasetKey].hasOwnProperty('preventLayerToFront') && labMap.objDatasets[datasetKey].preventLayerToFront === true) labMap.preventLayerToFront = true;
}
catch (e) {
labError(new LabException("Error attempting to create GeoJSON Leaflet layer: " + e.message));
}
}
else {
labError(new LabException("Couldn't find URL: " + labMap.objDatasets[datasetKey].url));
}
stopLabSpinner() // remove the spinner as the data has loaded
});
}
else {
// No dataset found so reset the map to the initial state
document.title = 'Trafford Data Lab: ' + labMap.title
labMap.updateAbout(labMap.about);
updateMapStateUrl('dataset', null); // remove the dataset key from the URL hash
updateMapStateUrl('cluster', null); // remove the cluster key from the URL hash
}
}
// Handles clustering and de-clustering of point data - called via click event on clustering checkbox
function toggleClustering() {
labMap.datasetLayer.removeFrom(labMap.map);
if (document.getElementById('toggleClustering').checked) {
labMap.datasetLayer = labMap.datasetCluster; // the layer we are going to add to the map is the clustered version
updateMapStateUrl('cluster', 'true');
}
else {
labMap.datasetLayer = labMap.datasetGeoJson; // the layer we are going to add to the map is the straight GeoJSON we loaded
updateMapStateUrl('cluster', 'false'); // update the URL hash to reflect that the user has specifically removed the clustering
}
labMap.datasetLayer.addTo(labMap.map);
}
// Determines whether the layer provided is an isoline - created by the reachability plugin
function isIsolineLayer(layer) {
if (labMap.reachabilityControl != null && labMap.reachabilityControl.isolinesGroup != null) {
/*
The following iteration is seemingly required as the expected code: labMap.reachabilityControl.isolinesGroup.hasLayer(layer) doesn't work.
Each isoline or set of isolines (if intervals were created) are added to .isolinesGroup as a L.geoJSON object, thus they are effectively sub groups of .isolinesGroup.
The loop iterates through each sub group and checks if the layer is present. If so we stop checking.
*/
var arrGroups = labMap.reachabilityControl.isolinesGroup.getLayers();
for (var i = 0; i < arrGroups.length; i++) {
if (arrGroups[i].hasLayer(layer)) return true;
}
}
return false;
}
// Determines whether the layer provided is a geography boundary
function isGeographyLayer(layer) {
for (key in labMap.objGeographies) {
if (labMap.objGeographies[key].hasLayer(layer)) return true;
}
return false;
}
// Determines whether the layer provided is a dataset layer
function isDatasetLayer(layer) {
return (labMap.datasetLayer != null && labMap.datasetLayer.hasLayer(layer));
}
// Function to format the property keys of a given dataset, e.g. makes "area_name" into "Area name" so that it looks nice in the info panel
function formatPropertyKey(key) {
key = key.replace(/_/g, " "); // remove and underscore characters and replace with spaces
return key.substring(0, 1).toUpperCase() + key.substring(1); // capitalise the first character and then return the result
}
// Error functions for vector tile layers
/*
The error event is fired by mapbox-gl.js and listened for in leaflet-mapbox-gl.js.
From there the error function specified in the options parameter of the L.mapboxGL object is called.
At this point the layer has already been created and added to the map, hence why in the functions below the layer is first removed from the map and destroyed before the alternative is created.
This is due to the difference in the way vector tiles and raster tiles are instantiated.
*/
function vectorTileErrorZoomstackLight(e) {
labMap.baseLayers.Light.removeFrom(labMap.map);
labMap.baseLayers.Light = labCreateTileLayer('CartoDB.Positron');
labMap.baseLayers.Light.addTo(labMap.map);
labMap.updateLayerControl();
}
function vectorTileErrorZoomstackOutdoor(e) {
labMap.baseLayers.Outdoor.removeFrom(labMap.map);
labMap.baseLayers.Outdoor = labCreateTileLayer('OpenStreetMap.Hot');
labMap.baseLayers.Outdoor.addTo(labMap.map);
labMap.updateLayerControl();
}
function vectorTileErrorZoomstackRoad(e) {
labMap.baseLayers.Road.removeFrom(labMap.map);
labMap.baseLayers.Road = labCreateTileLayer('OpenStreetMap.Mapnik');
labMap.baseLayers.Road.addTo(labMap.map);
labMap.updateLayerControl();
}
// Updates the hash component of the URL with dataset, zoom and latlng coordinates key/value pairs in order to allow users to share the current state of the map
function updateMapStateUrl(key, value) {
var zoom, latlng, dataset, cluster;
zoom = (key == 'zoom') ? value : getZoomHash();
latlng = (key == 'latlng') ? value : getLatLngHash();
dataset = (key == 'dataset') ? value : getDatasetHash();
cluster = (key == 'cluster') ? value : getClusterHash();
var newHash = '';
if (zoom != null) newHash = 'zoom=' + zoom;
if (latlng != null) {
if (newHash != '') newHash += '&';
newHash += 'latlng=' + latlng;
}
if (dataset != null) {
if (newHash != '') newHash += '&';
newHash += 'dataset=' + dataset;
}
if (cluster != null) {
if (newHash != '') newHash += '&';
newHash += 'cluster=' + cluster;
}
location.hash = newHash;
// Update the URL in the hidden text field for the share button
var shareUrl = document.getElementById("shareUrl");
shareUrl.value = location.href;
L.DomUtil.addClass(labMap.shareBtn, 'shareButtonActive'); // Make the share button orange again to indicate that the URL has changed
}
// Obtains the value of the zoom passed via the URL hash
function getZoomHash() {
var zoom = parseFloat(labGetQryStrValByKey('zoom', location.hash));
// Zoom value must be a number between the minimum and maximum defined when the labMap object is initialised
return (isNaN(zoom) == false && zoom >= labMap.attributes.minZoom && zoom <= labMap.attributes.maxZoom) ? zoom : null;
}
// Obtains the value of the latlng passed via the URL hash
function getLatLngHash() {
return labGetQryStrValByKey('latlng', location.hash);
}
// Obtains the value of the dataset passed via the URL hash
function getDatasetHash() {
return labGetQryStrValByKey('dataset', location.hash);
}
// Obtains the value of the cluster state (of point data only) passed via the URL hash
function getClusterHash() {
return labGetQryStrValByKey('cluster', location.hash);
}
// ######### INITIALISATION #########
// Set up the basic map environment
var labMap = new LabLeafletMap({
title: 'Explore',
about: 'Discover the different geographies within Trafford by choosing a layer and then selecting an area.',
baseLayers: {}, // Override the default baselayers in LabMap so that we can use OS Zoomstack vector layers if possible
attributes: { // Override the default attributes in LabMap so that we can specify the maxBounds - the OS Zoomstack vector layers only cover Great Britain
center: [53.4189, -2.33],
zoom: 12,
minZoom: 10,
maxZoom: 18,
zoomDelta: 0.25,
zoomSnap: 0,
maxBounds: [[ 49.84 , -8.74 ], [ 60.9, 1.96 ]] // fix map view to the extent of Great Britain
}
});
// legend toggle button
labMap.shareBtn = document.createElement('div'); // creating the toggle button..
labMap.shareBtn.setAttribute('title', 'Share - copy map link to clipboard'); // ..add the tooltip..
labMap.shareBtn.setAttribute('class', 'fa fa-share-alt-square toggleGadget shareButton shareButtonActive'); // ..the CSS..
labMap.shareBtn.addEventListener('click', function () { // ..and the click event..
try {
// Copy the URL to the clipboard from the text box element
var shareUrl = document.getElementById("shareUrl");
shareUrl.select(); // try to select the content of the text box...
shareUrl.setSelectionRange(0, shareUrl.value.length); // ...but use this if the browser doesn't support .select() (mainly iOS devices)
document.execCommand("copy");
}
catch(e) {
// The copy to clipboard failed so show message instead
alert('Please copy the URL in the address bar to share this map.');
}
L.DomUtil.removeClass(labMap.shareBtn, 'shareButtonActive');
});
labMap.titleContainer.appendChild(labMap.shareBtn);
if (supportWebGL()) {
/*
Attempt to create vector tile base layers.
If an error occurs we fallback to using raster tile layers (and they have built in fallback in case the tile URL can't be loaded).
*/
labMap.baseLayers = {
'Light': labCreateVectorTileLayer('OSZoomstack.Light'),
'Outdoor': labCreateVectorTileLayer('OSZoomstack.Outdoor'),
'Road': labCreateVectorTileLayer('OSZoomstack.Road'),
'White': labCreateTileLayer(null)
}
}
else {
// Fallback to use raster tile layers instead of vector.
labMap.baseLayers = {
'Light': labCreateTileLayer('CartoDB.Positron'),
'Outdoor': labCreateTileLayer('OpenStreetMap.Hot'),
'Road': labCreateTileLayer('OpenStreetMap.Mapnik'),
'White': labCreateTileLayer(null)
}
}
labMap.updateLayerControl(); // update the layer control with the raster tile layers
labMap.baseLayers.Light.addTo(labMap.map); // choose the initial base/tile layer for the map
// Add the isochrones plugin
labMap.reachabilityControl = labSetupReachabilityPlugin({
// Common options are taken care of in the function, however the options below are extra
styleFn: labStyleIsolines,
clickFn: showLayerProps,
pane: 'pane_geography_overlay',
attributes: '"area","total_pop"'
});
labMap.reachabilityControl.addTo(labMap.map);
labMap.datasetGeoJson = null; // object to store GeoJSON created from datasets loaded from the select list. ***NOTE*** this object is important for the resetting of styles for clusered marker datasets
labMap.datasetCluster = null; // object to store a leaflet.markercluster object - created if the dataset contains point data
labMap.datasetLayer = null; // either a copy of labMap.datasetGeoJson or labMap.datasetCluster containing labMap.datasetGeoJson layers - depends on whether we are clustering point data or not
labMap.featureCache = null; // for caching the currently selected feature
// Polygon feature styling
labMap.poly = {
color: '#212121',
weight: 2,
fillOpacity: 0
};
// Selected polygon styling
labMap.polySelected = {
color: '#ffea00',
weight: 5,
opacity: '1'
};
// ######### EVENTS #########
// Reset the map state if any features have been selected
labMap.map.on('click', (function (e) {
resetFeatureStyle(); // reset the style of a previously selected feature
labMap.updateInfo(); // clear and hide the info panel
}));
labMap.map.on('reachability:api_call_start', function (e) {
// indicate to the user that something is happening at the start of the API call
startLabSpinner();
});
labMap.map.on('reachability:api_call_end', function (e) {
// stop the spinner at the end of the API call
stopLabSpinner();
});
labMap.map.on('reachability:delete', function (e) {
// Check that the recently deleted isoline wasn't currently selected
if (labMap.featureCache != null) {
var layer = labMap.featureCache;
if (isIsolineLayer(layer) == false && isGeographyLayer(layer) == false && isDatasetLayer(layer) == false) {
// The currently cached layer must've been an isoline which has now been deleted so reset the info panel and cache
labMap.updateInfo();
labMap.featureCache = null;
}
}
});
labMap.map.on('zoomend', function (e) {
// Update the URL with the new zoom level
updateMapStateUrl('zoom', labMap.map.getZoom());
});
labMap.map.on('moveend', function (e) {
// Get the new centre coordinate of the map
var mapCentre = labMap.map.getCenter();
// Update the URL with the new latlng
updateMapStateUrl('latlng', encodeURIComponent(mapCentre.lat + ' ' + mapCentre.lng));
});
// ######### DATASET METADATA & SELECTION UI #########
labAjax('datasets.json', function (data) {
// Load the JSON holding the metadata for all the datasets which we can visualise in Explore, in the form:
/*
"": {
"title": "",
"about": "",
"attribution": "",
"url": "",
"theme": "",
"cluster": true, // OPTIONAL
"hidden": true, // OPTIONAL
"legend": "" // OPTIONAL
}
*/
labMap.objDatasets = data; // store the dataset data
var arrSelectList = []; // array to hold the contents of the select list to choose the dataset to visualise
// Loop through the labMap.objDatasets object adding the main key, title and theme to the array so long as the key is a dataset and we don't want it hidden
for (key in labMap.objDatasets) {
if (labMap.objDatasets.hasOwnProperty(key) && (!labMap.objDatasets[key].hasOwnProperty('hidden') || (labMap.objDatasets[key].hasOwnProperty('hidden') && labMap.objDatasets[key].hidden !== true))) {
arrSelectList.push({ dataset: key, title: labMap.objDatasets[key].title, theme: labMap.objDatasets[key].theme });
}
}
// Sort the select list array by the themes first as these form the optgroup headings, then by the dataset titles
arrSelectList.sort(function(a, b) {
var themeA = a.theme.toLowerCase();
var themeB = b.theme.toLowerCase();
var titleA = a.title.toLowerCase();
var titleB = b.title.toLowerCase();
// attempt sorting by theme first
if (themeA < themeB) return -1;
if (themeA > themeB) return 1;
// if the theme is the same, sort by the title
if (titleA < titleB) return -1;
if (titleA > titleB) return 1;
return 0;
});
// Check the URL for a dataset key in the URL
var datasetQS = getDatasetHash();
// Create the select element to choose the labMap.objDatasets
var datasetSelect = '<select name="frmDatasetList" onChange="loadDatasetLayer(this.value, true)" class="datasetSelect"><option value="" selected="selected">Select a dataset to visualise...</option>';
var optGroupTheme = ''; // ensure we create new optgroup tags based on the themes
for (var i = 0; i < arrSelectList.length; i++) {
// Write out new optgroup tag
if (optGroupTheme != arrSelectList[i].theme) {
if (optGroupTheme != '') datasetSelect += '</optgroup>';
datasetSelect += '<optgroup label="' + arrSelectList[i].theme + '">';
optGroupTheme = arrSelectList[i].theme;
}
// Write out the dataset list
datasetSelect += '<option value="' + arrSelectList[i].dataset + '"';
if (datasetQS == arrSelectList[i].dataset) datasetSelect += ' selected="selected"';
datasetSelect += '>' + arrSelectList[i].title + '</option>';
}
datasetSelect += '</optgroup></select>';
// Add the dataset chooser UI to the filter container along with the element to toggle point data clustering
labMap.updateFilterGUI(datasetSelect + '<div id="toggleClusteringContainer" class="hideContent"><input type="checkbox" id="toggleClustering" onClick="toggleClustering()"/><label for="toggleClustering" class="toggleCluster">cluster markers</label></div>');
// Store a reference to the checkbox and container for the point data clustering control so that we can show/hide by adding or removing a CSS class, check/uncheck it etc.
labMap.toggleCluster = document.getElementById('toggleClustering');
labMap.toggleClusterContainer = document.getElementById('toggleClusteringContainer');
// If a dataset has been specified via the QueryString, attempt to load it
if (datasetQS !== null) loadDatasetLayer(datasetQS, false);
});
// ######### SPATIAL GEOGRAPHY LAYERS/LABELS #########
labMap.objGeographies = {}; // object to hold all the boundary L.geoJSON objects so that we can test in a loop for which layer belongs to which geography
// Add the Trafford boundary
labAjax('https://www.trafforddatalab.io/spatial_data/local_authority/2021/trafford_local_authority_full_resolution.geojson', function (data) {
labMap.objGeographies['LA'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents }).addTo(labMap.map);
try {
// We need to see if we have a zoom and latlng provided in the URL - if so we need to go to that point on the map, otherwise fit to the boundary of Trafford
var zoom = getZoomHash();
var latlng = getLatLngHash();
if (zoom == null && latlng == null) {
labMap.map.fitBounds(labMap.objGeographies['LA'].getBounds()); // adjust the zoom to fit the boundary to the screen size
}
else if (zoom != null && latlng != null) {
labMap.map.setView(L.latLng(latlng.split(' ')), zoom); // zoom and move the map to the values provided in the URL hash
}
else if (zoom != null) {
labMap.map.setZoom(zoom); // zoom in to the value provided in the URL hash
}
else {
labMap.map.panTo(L.latLng(latlng.split(' '))); // move the map to the latlng provided in the URL hash
}
}
catch (e) {
// There's been a problem with the zoom or latlng values in the URL hash so just fit to bounds of Trafford
labMap.map.fitBounds(labMap.objGeographies['LA'].getBounds()); // adjust the zoom to fit the boundary to the screen size
}
labMap.overlayLayers['1. Local authority'] = labMap.objGeographies['LA'];
labMap.updateLayerControl();
});
// Add Trafford wards (which came into effect from 2023-05-04)
labAjax('https://www.trafforddatalab.io/spatial_data/ward/2023/trafford_ward_full_resolution.geojson', function (data) {
labMap.objGeographies['Ward'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents });
labMap.overlayLayers['2. Wards'] = labMap.objGeographies['Ward'];
labMap.updateLayerControl();
});
// Add Trafford localities (which came into effect from 2023-05-04)
labAjax('https://www.trafforddatalab.io/spatial_data/council_defined/2023/trafford_localities_full_resolution.geojson', function (data) {
labMap.objGeographies['Localities'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents });
labMap.overlayLayers['3. Localities'] = labMap.objGeographies['Localities'];
labMap.updateLayerControl();
});
// Add the Trafford MSOAs
labAjax('https://www.trafforddatalab.io/spatial_data/msoa/2021/trafford_msoa_full_resolution.geojson', function (data) {
labMap.objGeographies['MSOA'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents });
labMap.overlayLayers['4. MSOA'] = labMap.objGeographies['MSOA'];
labMap.updateLayerControl();
});
// Add the Trafford LSOAs
labAjax('https://www.trafforddatalab.io/spatial_data/lsoa/2021/trafford_lsoa_full_resolution.geojson', function (data) {
labMap.objGeographies['LSOA'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents });
labMap.overlayLayers['5. LSOA'] = labMap.objGeographies['LSOA'];
labMap.updateLayerControl();
});
// Add the Trafford OAs
labAjax('https://www.trafforddatalab.io/spatial_data/oa/2021/trafford_oa_full_resolution.geojson', function (data) {
labMap.objGeographies['OA'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents });
labMap.overlayLayers['6. OA'] = labMap.objGeographies['OA'];
labMap.updateLayerControl();
});
// Add labels for the town centres - this is not a boundary layer so it is not added to objGeographies
labAjax('https://www.trafforddatalab.io/spatial_data/town_centres/trafford_town_centres.geojson', function (data) {
labMap.overlayLayers['7. Town centres'] = L.geoJSON(data, {
pointToLayer: function (feature, latlng) {
return L.marker(latlng, { icon: L.divIcon({ iconSize: null }) }).bindTooltip(feature.properties.name, { direction: 'center', className: 'labLabels', opacity: 1, permanent: true });
}
});
labMap.updateLayerControl();
});
// Add the Trafford Creative Clusters
labAjax('https://www.trafforddatalab.io/spatial_data/council_defined/2024/trafford_creative_clusters_full_resolution.geojson', function (data) {
labMap.objGeographies['Creative_Clusters'] = L.geoJSON(data, { attribution: labMap.attributionOS, style: labMap.poly, onEachFeature: featureEvents });
labMap.overlayLayers['8. Creative Clusters'] = labMap.objGeographies['Creative_Clusters'];
labMap.updateLayerControl();
});
</script>
</body>
</html>