-
Notifications
You must be signed in to change notification settings - Fork 16
/
Util.js
1549 lines (1438 loc) · 51.7 KB
/
Util.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
/* global M */
import { bounds, latLngBounds, point, latLng } from 'leaflet';
import proj4 from 'proj4';
export const Util = {
// _convertAndFormatPCRS returns the converted CRS and formatted pcrsBounds in gcrs, pcrs, tcrs, and tilematrix. Used for setting extent for the map and layer (map.extent, layer.extent).
// _convertAndFormatPCRS: Bounds, _map, projection -> {...}
_convertAndFormatPCRS: function (pcrsBounds, crs, projection) {
if (!pcrsBounds || !crs) return {};
let tcrsTopLeft = [],
tcrsBottomRight = [],
tileMatrixTopLeft = [],
tileMatrixBottomRight = [],
tileSize = crs.options.crs.tile.bounds.max.y;
for (let i = 0; i < crs.options.resolutions.length; i++) {
let scale = crs.scale(i),
minConverted = crs.transformation.transform(pcrsBounds.min, scale),
maxConverted = crs.transformation.transform(pcrsBounds.max, scale);
tcrsTopLeft.push({
horizontal: minConverted.x,
vertical: maxConverted.y
});
tcrsBottomRight.push({
horizontal: maxConverted.x,
vertical: minConverted.y
});
//converts the tcrs values from earlier to tilematrix
tileMatrixTopLeft.push({
horizontal: tcrsTopLeft[i].horizontal / tileSize,
vertical: tcrsTopLeft[i].vertical / tileSize
});
tileMatrixBottomRight.push({
horizontal: tcrsBottomRight[i].horizontal / tileSize,
vertical: tcrsBottomRight[i].vertical / tileSize
});
}
//converts the gcrs, I believe it can take any number values from -inf to +inf
let unprojectedMin = crs.unproject(pcrsBounds.min),
unprojectedMax = crs.unproject(pcrsBounds.max);
let gcrs = {
topLeft: {
horizontal: unprojectedMin.lng,
vertical: unprojectedMax.lat
},
bottomRight: {
horizontal: unprojectedMax.lng,
vertical: unprojectedMin.lat
}
};
//formats known pcrs bounds to correct format
let pcrs = {
topLeft: {
horizontal: pcrsBounds.min.x,
vertical: pcrsBounds.max.y
},
bottomRight: {
horizontal: pcrsBounds.max.x,
vertical: pcrsBounds.min.y
}
};
//formats all extent data
let extent = {
topLeft: {
tcrs: tcrsTopLeft,
tilematrix: tileMatrixTopLeft,
gcrs: gcrs.topLeft,
pcrs: pcrs.topLeft
},
bottomRight: {
tcrs: tcrsBottomRight,
tilematrix: tileMatrixBottomRight,
gcrs: gcrs.bottomRight,
pcrs: pcrs.bottomRight
}
};
if (projection) {
extent.projection = projection;
}
return extent;
},
// extentToBounds: returns bounds in gcrs, pcrs. Used for setting bounds for the map (map.totalLayerBounds).
// extentToBounds: {...}, crs -> Bounds / LatlngBounds
extentToBounds(extent, crs) {
switch (crs.toUpperCase()) {
case 'PCRS':
return bounds(
point(extent.topLeft.pcrs.horizontal, extent.topLeft.pcrs.vertical),
point(
extent.bottomRight.pcrs.horizontal,
extent.bottomRight.pcrs.vertical
)
);
case 'GCRS':
return latLngBounds(
latLng(extent.topLeft.gcrs.vertical, extent.topLeft.gcrs.horizontal),
latLng(
extent.bottomRight.gcrs.vertical,
extent.bottomRight.gcrs.horizontal
)
);
}
},
// axisToCS returns the CRS when given the axis:
// https://maps4html.org/web-map-doc/docs/elements/input/#axis
// axisToCS: (Axis String) -> (CRS String)
axisToCS: function (axis) {
try {
switch (axis.toLowerCase()) {
case 'row':
case 'column':
return 'TILEMATRIX';
case 'i':
case 'j':
return ['MAP', 'TILE'];
case 'x':
case 'y':
return 'TCRS';
case 'latitude':
case 'longitude':
return 'GCRS';
case 'northing':
case 'easting':
return 'PCRS';
default:
return M.FALLBACK_CS;
}
} catch (e) {
return undefined;
}
},
// csToAxes takes a given cs and retuns the axes, first horizontal then vertical
// https://maps4html.org/web-map-doc/docs/elements/input/#axis
// csToAxes: (CRS String) -> [(horizontal axis String), (Vertical axis String)]
csToAxes: function (cs) {
try {
switch (cs.toLowerCase()) {
case 'tilematrix':
return ['column', 'row'];
case 'map':
case 'tile':
return ['i', 'j'];
case 'tcrs':
return ['x', 'y'];
case 'gcrs':
return ['longitude', 'latitude'];
case 'pcrs':
return ['easting', 'northing'];
}
} catch (e) {
return undefined;
}
},
// axisToXY takes horizontal axis and returns 'x', or takes vertical axis and returns 'y'
// https://maps4html.org/web-map-doc/docs/elements/input/#axis
// axisToXY: (Axis String) -> 'x' or 'y'
axisToXY: function (axis) {
try {
switch (axis.toLowerCase()) {
case 'i':
case 'column':
case 'longitude':
case 'x':
case 'easting':
return 'x';
case 'row':
case 'j':
case 'latitude':
case 'y':
case 'northing':
return 'y';
default:
return undefined;
}
} catch (e) {
return undefined;
}
},
// convertPCRSBounds converts pcrsBounds to the given cs Bounds.
// convertPCRSBounds: Bounds, Int, CRS, Str('PCRS'|'TCRS'|'TILEMATRIX'|'GCRS') -> Bounds
convertPCRSBounds: function (pcrsBounds, zoom, projection, cs) {
if (
!pcrsBounds ||
(!zoom && zoom !== 0) ||
!Number.isFinite(+zoom) ||
!projection ||
!cs
)
return undefined;
projection = typeof projection === 'string' ? M[projection] : projection;
switch (cs.toUpperCase()) {
case 'PCRS':
return pcrsBounds;
case 'TCRS':
case 'TILEMATRIX':
let minPixel = projection.transformation.transform(
pcrsBounds.min,
projection.scale(+zoom)
),
maxPixel = projection.transformation.transform(
pcrsBounds.max,
projection.scale(+zoom)
);
if (cs.toUpperCase() === 'TCRS') return bounds(minPixel, maxPixel);
let tileSize = projection.options.crs.tile.bounds.max.x;
return bounds(
point(minPixel.x / tileSize, minPixel.y / tileSize),
point(maxPixel.x / tileSize, maxPixel.y / tileSize)
);
case 'GCRS':
let minGCRS = projection.unproject(pcrsBounds.min),
maxGCRS = projection.unproject(pcrsBounds.max);
return bounds(
point(minGCRS.lng, minGCRS.lat),
point(maxGCRS.lng, maxGCRS.lat)
);
default:
return undefined;
}
},
// pointToPCRSPoint takes a point, with a projection and cs and converts it to a pcrs point/latLng
//pointToPCRSPoint: Point, Int, CRS, Str('PCRS'|'TCRS'|'TILEMATRIX'|'GCRS') -> point|latLng
pointToPCRSPoint: function (pt, zoom, projection, cs) {
if (
!pt ||
(zoom !== undefined && !Number.isFinite(+zoom)) ||
(zoom === undefined &&
(cs === 'TILEMATRIX' || cs === 'TCRS' || cs === 'TILE')) ||
!cs ||
!projection
)
return undefined;
projection = typeof projection === 'string' ? M[projection] : projection;
let tileSize = projection.options.crs.tile.bounds.max.x;
switch (cs.toUpperCase()) {
case 'TILEMATRIX':
return Util.pixelToPCRSPoint(
point(pt.x * tileSize, pt.y * tileSize),
zoom,
projection
);
case 'PCRS':
return pt;
case 'TCRS' || 'TILE':
return Util.pixelToPCRSPoint(pt, zoom, projection);
case 'GCRS':
return projection.project(latLng(pt.y, pt.x));
default:
return undefined;
}
},
// pixelToPCRSPoint takes a pixel point, the zoom and projection and returns a point in pcrs
// pixelToPCRSPoint: Point, Int, CRS|Str -> point
pixelToPCRSPoint: function (point, zoom, projection) {
if (
!point ||
(!zoom && zoom !== 0) ||
!Number.isFinite(+zoom) ||
!projection
)
return undefined;
projection = typeof projection === 'string' ? M[projection] : projection;
return projection.transformation.untransform(point, projection.scale(zoom));
},
// boundsToPCRSBounds converts bounds with projection and cs to PCRS bounds
// boundsToPCRSBounds: bounds, Int, CRS|Str, Str('PCRS'|'TCRS'|'TILEMATRIX'|'GCRS') -> bounds
boundsToPCRSBounds: function (bnds, zoom, projection, cs) {
if (
!bnds ||
!bnds.max ||
!bnds.min ||
(zoom !== undefined && !Number.isFinite(+zoom)) ||
(zoom === undefined &&
(cs === 'TILEMATRIX' || cs === 'TCRS' || cs === 'TILE')) ||
!projection ||
!cs
)
return undefined;
projection = typeof projection === 'string' ? M[projection] : projection;
return bounds(
Util.pointToPCRSPoint(bnds.min, zoom, projection, cs),
Util.pointToPCRSPoint(bnds.max, zoom, projection, cs)
);
},
//bounds have fixed point positions, where min is always topleft, max is always bottom right, and the values are always sorted by leaflet
//important to consider when working with pcrs where the origin is not topleft but rather bottomleft, could lead to confusion
pixelToPCRSBounds: function (bnds, zoom, projection) {
if (
!bnds ||
!bnds.max ||
!bnds.min ||
(!zoom && zoom !== 0) ||
!Number.isFinite(+zoom) ||
!projection
)
return undefined;
projection = typeof projection === 'string' ? M[projection] : projection;
return bounds(
Util.pixelToPCRSPoint(bnds.min, zoom, projection),
Util.pixelToPCRSPoint(bnds.max, zoom, projection)
);
},
//meta content is the content attribute of meta
// input "max=5,min=4" => [[max,5][min,5]]
_metaContentToObject: function (input) {
if (!input || input instanceof Object) return {};
let content = input.split(/\s+/).join('');
let contentArray = {};
let stringSplit = content.split(',');
for (let i = 0; i < stringSplit.length; i++) {
let prop = stringSplit[i].split('=');
if (prop.length === 2) contentArray[prop[0]] = prop[1];
}
if (contentArray !== '' && stringSplit[0].split('=').length === 1)
contentArray.content = stringSplit[0];
return contentArray;
},
// _coordsToArray returns an array of arrays of coordinate pairs
// _coordsToArray: ("1,2,3,4") -> [[1,2],[3,4]]
_coordsToArray: function (containerPoints) {
for (
var i = 1, pairs = [], coords = containerPoints.split(',');
i < coords.length;
i += 2
) {
pairs.push([parseInt(coords[i - 1]), parseInt(coords[i])]);
}
return pairs;
},
// _splitCoordinate splits string coordinates to an array as floating point numbers
_splitCoordinate: function (element, index, array) {
var a = [];
element.split(/\s+/gim).forEach(Util._parseNumber, a);
this.push(a);
},
// _parseNumber parses a string as a floating point number, helper function for _splitCoordinate
_parseNumber: function (element, index, array) {
this.push(parseFloat(element));
},
// _handleLink handles map-a links, when clicked on a map-a link
_handleLink: function (link, leafletLayer) {
let zoomTo,
justPan = false,
layer,
map = leafletLayer._map,
opacity;
if (link.type === 'text/html' && link.target !== '_blank') {
// all other target values other than blank behave as _top
link.target = '_top';
} else if (link.type !== 'text/html' && link.url.includes('#')) {
let hash = link.url.split('#'),
loc = hash[1].split(',');
zoomTo = { z: loc[0] || 0, lng: loc[1] || 0, lat: loc[2] || 0 };
justPan = !hash[0]; // if the first half of the array is an empty string then the link is just for panning
if (['/', '.', '#'].includes(link.url[0])) link.target = '_self';
}
if (!justPan) {
layer = document.createElement('map-layer');
layer.setAttribute('src', link.url);
layer.setAttribute('checked', '');
switch (link.target) {
case '_blank':
if (link.type === 'text/html') {
window.open(link.url);
} else {
postTraversalSetup();
map.options.mapEl.appendChild(layer);
}
break;
case '_parent':
postTraversalSetup();
for (let l of map.options.mapEl.querySelectorAll('map-layer,layer-'))
if (l._layer !== leafletLayer) map.options.mapEl.removeChild(l);
map.options.mapEl.appendChild(layer);
map.options.mapEl.removeChild(leafletLayer._layerEl);
break;
case '_top':
window.location.href = link.url;
break;
default:
postTraversalSetup();
opacity = leafletLayer._layerEl.opacity;
leafletLayer._layerEl.insertAdjacentElement('beforebegin', layer);
map.options.mapEl.removeChild(leafletLayer._layerEl);
}
} else if (zoomTo && !link.inPlace && justPan) {
leafletLayer._map.options.mapEl.zoomTo(
+zoomTo.lat,
+zoomTo.lng,
+zoomTo.z
);
if (opacity) layer.opacity = opacity;
map.getContainer().focus();
}
function postTraversalSetup() {
// when the projection is changed as part of the link traversal process,
// it's necessary to set the map viewer's lat, lon and zoom NOW, so that
// the promises that are created when the viewer's projection is changed
// can use the viewer's lat, lon and zoom properties that were in effect
// before the projection change i.e. in the closure for that code
// see mapml-viewer / map is=web-map projection attributeChangedCallback
// specifically required for use cases like changing projection after
// link traversal, e.g. BC link here https://maps4html.org/experiments/linking/features/
if (!link.inPlace && zoomTo) updateMapZoomTo(zoomTo);
// the layer is newly created, so have to wait until it's fully init'd
// before setting properties.
layer.whenReady().then(() => {
// if the map projection isnt' changed by link traversal, it's necessary
// to perform pan/zoom operations after the layer is ready
if (!link.inPlace && zoomTo)
layer.parentElement.zoomTo(+zoomTo.lat, +zoomTo.lng, +zoomTo.z);
else if (!link.inPlace) layer.zoomTo();
// not sure if this is necessary
if (opacity) layer.opacity = opacity;
// this is necessary to display the FeatureIndexOverlay, I believe
map.getContainer().focus();
});
}
function updateMapZoomTo(zoomTo) {
// can't use mapEl.zoomTo(...) here, it's too slow!
map.options.mapEl.lat = +zoomTo.lat;
map.options.mapEl.lon = +zoomTo.lng;
map.options.mapEl.zoom = +zoomTo.z;
}
},
getBoundsFromMeta: function (mapml) {
if (!mapml) return null;
let cs,
pseudo = mapml instanceof ShadowRoot ? ':host' : ':scope',
projection =
(mapml.querySelector(pseudo + ' > map-meta[name=projection]') &&
Util._metaContentToObject(
mapml
.querySelector(pseudo + ' > map-meta[name=projection]')
.getAttribute('content')
).content.toUpperCase()) ||
M.FALLBACK_PROJECTION;
try {
let meta =
mapml.querySelector(pseudo + ' > map-meta[name=extent]') &&
Util._metaContentToObject(
mapml
.querySelector(pseudo + ' > map-meta[name=extent]')
.getAttribute('content')
);
let zoom = meta.zoom;
let metaKeys = Object.keys(meta);
for (let i = 0; i < metaKeys.length; i++) {
if (!metaKeys[i].includes('zoom')) {
cs = Util.axisToCS(metaKeys[i].split('-')[2]);
break;
}
}
// this could happen if the content didn't match the grammar for map-meta[name=extent]
if (cs === undefined) throw new Error('cs undefined when getting bounds');
// when cs is tilematrix, tcrs or tile, zoom is required.
// should throw / return null instead of trying to construct a bounds
if (
zoom === undefined &&
(cs === 'TILEMATRIX' || cs === 'TCRS' || cs === 'TILE')
)
throw new Error(
'map-meta[name=extent] zoom= parameter not provided for tcrs,tile or tilematrix bounds'
);
let axes = Util.csToAxes(cs);
return Util.boundsToPCRSBounds(
bounds(
point(+meta[`top-left-${axes[0]}`], +meta[`top-left-${axes[1]}`]),
point(
+meta[`bottom-right-${axes[0]}`],
+meta[`bottom-right-${axes[1]}`]
)
),
zoom,
projection,
cs
);
} catch (error) {
//if error then by default set the layer to osm and bounds to the entire map view
return Util.boundsToPCRSBounds(
M[projection].options.crs.tilematrix.bounds(0),
0,
projection,
cs
);
}
},
/**
* TODO Review and improve design logic with Aliyan
*
* Parses object from <map-meta name="zoom" content="...">
* @param {type} mapml
* @returns {minZoom, maxZoom, minNativeZoom, maxNativeZoom}
*/
getZoomBoundsFromMeta: function (mapml) {
if (!mapml) return null;
let pseudo = mapml instanceof ShadowRoot ? ':host' : ':scope';
let meta = Util._metaContentToObject(
mapml
.querySelector(pseudo + '> map-meta[name=zoom]')
.getAttribute('content')
);
if (meta.min && meta.max && meta.value)
return {
minZoom: +meta.min,
maxZoom: +meta.max,
minNativeZoom: +meta.value,
maxNativeZoom: +meta.value
};
else if (meta.min && meta.max)
return {
minZoom: +meta.min,
maxZoom: +meta.max
};
else if (meta.min)
return {
minZoom: +meta.min
};
else if (meta.max)
return {
maxZoom: +meta.max
};
},
getZoomBounds: function (mapml, nativeZoom) {
if (!mapml) return null;
let nMin = 100,
nMax = 0,
features = mapml.querySelectorAll('map-feature'),
meta,
projection;
for (let i = 0; i < features.length; i++) {
let lZoom = +features[i].getAttribute('zoom');
if (!features[i].getAttribute('zoom')) lZoom = nativeZoom;
nMax = Math.max(nMax, lZoom);
nMin = Math.min(nMin, lZoom);
}
try {
projection = Util._metaContentToObject(
mapml.querySelector('map-meta[name=projection]').getAttribute('content')
).content;
meta = Util._metaContentToObject(
mapml.querySelector('map-meta[name=zoom]').getAttribute('content')
);
} catch (error) {
return {
minZoom: 0,
maxZoom:
M[projection || M.FALLBACK_PROJECTION].options.resolutions.length - 1,
minNativeZoom: nMin,
maxNativeZoom: nMax
};
}
return {
minZoom: +meta.min,
maxZoom: +meta.max,
minNativeZoom: nMin,
maxNativeZoom: nMax
};
},
// getNativeVariables: returns an object with the native zoom and CS,
// based on the map-metas that are available within
// the layer or the fallback default values.
// getNativeVariables: mapml-||map-layer||null||[map-feature,...] -> {zoom: _, val: _}
// mapml can be a mapml- element, map-layer element, null, or an array of map-features
getNativeVariables: function (mapml) {
let nativeZoom, nativeCS;
// when mapml is an array of features provided by the query
if (
mapml.length &&
mapml[0].parentElement.parentElement &&
mapml[0].parentElement.parentElement.tagName === 'mapml-'
) {
let mapmlEl = mapml[0].parentElement.parentElement;
nativeZoom =
(mapmlEl.querySelector &&
mapmlEl.querySelector('map-meta[name=zoom]') &&
+Util._metaContentToObject(
mapmlEl.querySelector('map-meta[name=zoom]').getAttribute('content')
).value) ||
0;
nativeCS =
(mapmlEl.querySelector &&
mapmlEl.querySelector('map-meta[name=cs]') &&
Util._metaContentToObject(
mapmlEl.querySelector('map-meta[name=cs]').getAttribute('content')
).content) ||
'GCRS';
} else {
// when mapml is null or a map-layer/mapml- element
nativeZoom =
(mapml.querySelector &&
mapml.querySelector('map-meta[name=zoom]') &&
+Util._metaContentToObject(
mapml.querySelector('map-meta[name=zoom]').getAttribute('content')
).value) ||
0;
nativeCS =
(mapml.querySelector &&
mapml.querySelector('map-meta[name=cs]') &&
Util._metaContentToObject(
mapml.querySelector('map-meta[name=cs]').getAttribute('content')
).content) ||
'GCRS';
}
return { zoom: nativeZoom, cs: nativeCS };
},
// _gcrsToTileMatrix returns the [column, row] of the tiles at map center. Used for Announce movement for screen readers
// _gcrsToTileMatrix: map/mapml-viewer -> [column, row]
_gcrsToTileMatrix: function (mapEl) {
let pt0 = mapEl._map.project(mapEl._map.getCenter());
let tileSize = mapEl._map.options.crs.options.crs.tile.bounds.max.y;
let column = Math.trunc(pt0.x / tileSize);
let row = Math.trunc(pt0.y / tileSize);
return [column, row];
},
// Pastes text to a mapml-viewer/map element(mapEl), text can be a mapml link, geojson, or a map-layer
// used for pasting layers through ctrl+v, drag/drop, and pasting through the contextmenu
// _pasteLayer: HTMLElement Str -> None
// Effects: append a map-layer element to mapEl, if it is valid
_pasteLayer: function (mapEl, text) {
try {
new URL(text);
// create a new <map-layer> child of the <mapml-viewer> element
let l =
'<map-layer src="' +
text +
'" label="' +
mapEl.locale.dfLayer +
'" checked=""></map-layer>';
mapEl.insertAdjacentHTML('beforeend', l);
mapEl.lastElementChild.whenReady().catch(() => {
if (mapEl) {
// should invoke lifecyle callbacks automatically by removing it from DOM
mapEl.removeChild(mapEl.lastChild);
}
// garbage collect it
l = null;
});
} catch (err) {
text = text
.replace(/(<!--.*?-->)|(<!--[\S\s]+?-->)|(<!--[\S\s]*?$)/g, '')
.trim();
if (
text.slice(0, 10) === '<map-layer' &&
text.slice(-12) === '</map-layer>'
) {
mapEl.insertAdjacentHTML('beforeend', text);
} else if (
text.slice(0, 12) === '<map-feature' &&
text.slice(-14) === '</map-feature>'
) {
let layer =
`<map-layer label="${mapEl.locale.dfPastedLayer}" checked>
<map-meta name='projection' content='${mapEl.projection}'></map-meta>` +
text +
'</map-layer>';
mapEl.insertAdjacentHTML('beforeend', layer);
} else {
try {
mapEl.geojson2mapml(JSON.parse(text));
} catch {
console.log('Invalid Input!');
}
}
}
},
// Takes GeoJSON Properties to return an HTML table, helper function
// for geojson2mapml
// _properties2Table: geojsonPropertiesOBJ -> HTML Table
_properties2Table: function (json) {
let table = document.createElement('table');
// Creating a Table Header
let thead = table.createTHead();
let row = thead.insertRow();
let th1 = document.createElement('th');
let th2 = document.createElement('th');
th1.appendChild(document.createTextNode(M.options.locale.popupPropName));
th2.appendChild(document.createTextNode(M.options.locale.popupPropValue));
th1.setAttribute('role', 'columnheader');
th2.setAttribute('role', 'columnheader');
th1.setAttribute('scope', 'col');
th2.setAttribute('scope', 'col');
row.appendChild(th1);
row.appendChild(th2);
// Creating table body and populating it from the JSON
let tbody = table.createTBody();
for (let key in json) {
if (json.hasOwnProperty(key)) {
let row = tbody.insertRow();
let th = document.createElement('th');
let td = document.createElement('td');
th.appendChild(document.createTextNode(key));
td.appendChild(document.createTextNode(json[key]));
th.setAttribute('scope', 'row');
td.setAttribute('itemprop', key);
row.appendChild(th);
row.appendChild(td);
}
}
return table;
},
// Takes bbox array and a x,y coordinate to possibly update the extent, returns extent
// for geojson2mapml
// _updateExtent: [min x, min y, max x, max y], x, y -> [min x, min y, max x, max y]
_updateExtent: function (bboxExtent, x, y) {
if (bboxExtent === {}) {
return bboxExtent;
}
bboxExtent[0] = Math.min(x, bboxExtent[0]);
bboxExtent[1] = Math.min(y, bboxExtent[1]);
bboxExtent[2] = Math.max(x, bboxExtent[2]);
bboxExtent[3] = Math.max(y, bboxExtent[3]);
return bboxExtent;
},
// Takes a GeoJSON geojson and an options Object which returns a <map-layer> Element
// The options object can contain the following:
// label - String, contains the layer name, if included overrides the default label mapping
// projection - String, contains the projection of the layer (OSMTILE, WGS84, CBMTILE, APSTILE), defaults to OSMTILE
// caption - Function | String, function accepts one argument being the feature object which produces the featurecaption string OR a string that is the name of the property that will be mapped to featurecaption
// properties - Function | String | HTMLElement, a function which maps the geojson feature to an HTMLElement or a string that will be parsed as an HTMLElement or an HTMLElement
// geometryFunction - Function, A function you supply that can add classes, hyperlinks and spans to the created <map-geometry> element, default would be the plain map-geometry element
// geojson2mapml: geojson Object <map-layer> [min x, min y, max x, max y] -> <map-layer>
geojson2mapml: function (json, options = {}, layer = null, bboxExtent = {}) {
let defaults = {
label: null,
projection: 'OSMTILE',
caption: null,
properties: null,
geometryFunction: null
};
// assign default values for undefined options
options = Object.assign({}, defaults, options);
// If string json is received
if (typeof json === 'string') {
json = JSON.parse(json);
}
let geometryType = [
'POINT',
'LINESTRING',
'POLYGON',
'MULTIPOINT',
'MULTILINESTRING',
'MULTIPOLYGON',
'GEOMETRYCOLLECTION'
];
let jsonType = json.type.toUpperCase();
let out = '';
let setExtent = false;
// HTML parser
let parser = new DOMParser();
// initializing layer
if (layer === null) {
if (!json.bbox) {
setExtent = true;
}
// creating an empty mapml layer
let xmlStringLayer =
"<map-layer label='' checked><map-meta name='projection' content='" +
options.projection +
"'></map-meta><map-meta name='cs' content='gcrs'></map-meta></map-layer>";
layer = parser.parseFromString(xmlStringLayer, 'text/html');
//console.log(layer)
if (options.label !== null) {
layer.querySelector('map-layer').setAttribute('label', options.label);
} else if (json.name) {
layer.querySelector('map-layer').setAttribute('label', json.name);
} else if (json.title) {
layer.querySelector('map-layer').setAttribute('label', json.title);
} else {
layer
.querySelector('map-layer')
.setAttribute('label', M.options.locale.dfLayer);
}
}
let ptElStr = '<map-point></map-point>',
ptEl = parser.parseFromString(ptElStr, 'text/html');
let multiPoint =
'<map-multipoint><map-coordinates></map-coordinates></map-multipoint>';
multiPoint = parser.parseFromString(multiPoint, 'text/html');
let linestring =
'<map-linestring><map-coordinates></map-coordinates></map-linestring>';
linestring = parser.parseFromString(linestring, 'text/html');
let multilinestring = '<map-multilinestring></map-multilinestring>';
multilinestring = parser.parseFromString(multilinestring, 'text/html');
let polygon = '<map-polygon></map-polygon>';
polygon = parser.parseFromString(polygon, 'text/html');
let multiPolygon = '<map-multipolygon></map-multipolygon>';
multiPolygon = parser.parseFromString(multiPolygon, 'text/html');
let geometrycollection =
'<map-geometrycollection></map-geometrycollection>';
geometrycollection = parser.parseFromString(
geometrycollection,
'text/html'
);
let feature =
'<map-feature><map-featurecaption></map-featurecaption><map-geometry></map-geometry><map-properties></map-properties></map-feature>';
feature = parser.parseFromString(feature, 'text/html');
// Template to add coordinates to Geometries
let coords = '<map-coordinates></map-coordinates>';
coords = parser.parseFromString(coords, 'text/html');
//console.log(layer);
if (jsonType === 'FEATURECOLLECTION') {
// Setting bbox if it exists
if (json.bbox) {
layer
.querySelector('map-layer')
.insertAdjacentHTML(
'afterbegin',
"<map-meta name='extent' content='top-left-longitude=" +
json.bbox[0] +
', top-left-latitude=' +
json.bbox[1] +
', bottom-right-longitude=' +
json.bbox[2] +
',bottom-right-latitude=' +
json.bbox[3] +
"'></map-meta>"
);
} else {
bboxExtent = [
Infinity,
Infinity,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
];
}
let features = json.features;
//console.log("Features length - " + features.length);
for (let l = 0; l < features.length; l++) {
Util.geojson2mapml(features[l], options, layer, bboxExtent);
}
} else if (jsonType === 'FEATURE') {
let clone_feature = feature.cloneNode(true);
let curr_feature = clone_feature.querySelector('map-feature');
// Setting bbox if it exists
if (json.bbox) {
layer
.querySelector('map-layer')
.insertAdjacentHTML(
'afterbegin',
"<map-meta name='extent' content='top-left-longitude=" +
json.bbox[0] +
', top-left-latitude=' +
json.bbox[1] +
', bottom-right-longitude=' +
json.bbox[2] +
',bottom-right-latitude=' +
json.bbox[3] +
"'></map-meta>"
);
} else if (
typeof bboxExtent === 'object' &&
bboxExtent.length === undefined
) {
bboxExtent = [
Infinity,
Infinity,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
];
}
// Setting featurecaption
let featureCaption = layer
.querySelector('map-layer')
.getAttribute('label');
if (typeof options.caption === 'function') {
featureCaption = options.caption(json);
} else if (typeof options.caption === 'string') {
featureCaption = json.properties[options.caption];
// if property does not exist
if (featureCaption === undefined) {
featureCaption = options.caption;
}
} else if (json.id) {
// when no caption option available try setting id as featurecaption
featureCaption = json.id;
}
curr_feature.querySelector('map-featurecaption').innerHTML =
featureCaption;
// Setting Properties
let p;
// if properties function is passed
if (typeof options.properties === 'function') {
p = options.properties(json);
// if function output is not an element, ignore the properties.
if (!(p instanceof Element)) {
p = false;
console.error(
'options.properties function returns a string instead of an HTMLElement.'
);
}
} else if (typeof options.properties === 'string') {
// if properties string is passed
curr_feature
.querySelector('map-properties')
.insertAdjacentHTML('beforeend', options.properties);
p = false;
} else if (options.properties instanceof HTMLElement) {
// if an HTMLElement is passed - NOT TESTED
p = options.properties;
} else {
// If no properties function, string or HTMLElement is passed
p = Util._properties2Table(json.properties);
}
if (p) {
curr_feature.querySelector('map-properties').appendChild(p);
}
// Setting map-geometry
let g = Util.geojson2mapml(json.geometry, options, layer, bboxExtent);
if (typeof options.geometryFunction === 'function') {
curr_feature
.querySelector('map-geometry')
.appendChild(options.geometryFunction(g, json));
} else {
curr_feature.querySelector('map-geometry').appendChild(g);
}
// Appending feature to layer
layer.querySelector('map-layer').appendChild(curr_feature);
} else if (geometryType.includes(jsonType)) {
//console.log("Geometry Type - " + jsonType);
switch (jsonType) {
case 'POINT':
bboxExtent = Util._updateExtent(
bboxExtent,
json.coordinates[0],
json.coordinates[1]
);
out = json.coordinates[0] + ' ' + json.coordinates[1];
// Create Point element
let clone_point = ptEl.cloneNode(true);
clone_point = clone_point.querySelector('map-point');
// Create map-coords to add to the polygon
let clone_coords = coords.cloneNode(true);
clone_coords = clone_coords.querySelector('map-coordinates');
clone_coords.innerHTML = out;
clone_point.appendChild(clone_coords);
//console.log(clone_point);
return clone_point;