forked from Maps4HTML/MapML.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapml-viewer.js
1307 lines (1245 loc) · 40.1 KB
/
mapml-viewer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import './leaflet.js'; // bundled with proj4, proj4leaflet, modularized
import './mapml.js';
import DOMTokenList from './DOMTokenList.js';
import { MapLayer } from './layer.js';
import { MapCaption } from './map-caption.js';
import { MapFeature } from './map-feature.js';
import { MapExtent } from './map-extent.js';
export class MapViewer extends HTMLElement {
static get observedAttributes() {
return [
'lat',
'lon',
'zoom',
'projection',
'width',
'height',
'controls',
'static',
'controlslist'
];
}
// see comments below regarding attributeChangedCallback vs. getter/setter
// usage. Effectively, the user of the element must use the property, not
// the getAttribute/setAttribute/removeAttribute DOM API, because the latter
// calls don't result in the getter/setter being called (so you have to use
// the getter/setter directly)
get controls() {
return this.hasAttribute('controls');
}
set controls(value) {
const hasControls = Boolean(value);
if (hasControls) {
this.setAttribute('controls', '');
} else {
this.removeAttribute('controls');
}
}
get controlsList() {
return this._controlsList;
}
set controlsList(value) {
this._controlsList.value = value;
this.setAttribute('controlslist', value);
}
get width() {
return window.getComputedStyle(this).width.replace('px', '');
}
set width(val) {
//img.height or img.width setters change or add the corresponding attributes
this.setAttribute('width', val);
}
get height() {
return window.getComputedStyle(this).height.replace('px', '');
}
set height(val) {
//img.height or img.width setters change or add the corresponding attributes
this.setAttribute('height', val);
}
get lat() {
return this.hasAttribute('lat') ? this.getAttribute('lat') : '0';
}
set lat(val) {
if (val) {
this.setAttribute('lat', val);
}
}
get lon() {
return this.hasAttribute('lon') ? this.getAttribute('lon') : '0';
}
set lon(val) {
if (val) {
this.setAttribute('lon', val);
}
}
get projection() {
return this.hasAttribute('projection')
? this.getAttribute('projection')
: '';
}
set projection(val) {
if (val && M[val]) {
this.setAttribute('projection', val);
if (this._map && this._map.options.projection !== val) {
this._map.options.crs = M[val];
this._map.options.projection = val;
for (let layer of this.querySelectorAll('layer-')) {
layer.removeAttribute('disabled');
let reAttach = this.removeChild(layer);
this.appendChild(reAttach);
}
if (this._debug) for (let i = 0; i < 2; i++) this.toggleDebug();
} else this.dispatchEvent(new CustomEvent('createmap'));
} else throw new Error('Undefined Projection');
}
get zoom() {
return this.hasAttribute('zoom') ? this.getAttribute('zoom') : 0;
}
set zoom(val) {
var parsedVal = parseInt(val, 10);
if (!isNaN(parsedVal) && parsedVal >= 0 && parsedVal <= 25) {
this.setAttribute('zoom', parsedVal);
}
}
get layers() {
return this.getElementsByTagName('layer-');
}
get extent() {
let map = this._map,
pcrsBounds = M.pixelToPCRSBounds(
map.getPixelBounds(),
map.getZoom(),
map.options.projection
);
let formattedExtent = M._convertAndFormatPCRS(pcrsBounds, map);
if (map.getMaxZoom() !== Infinity) {
formattedExtent.zoom = {
minZoom: map.getMinZoom(),
maxZoom: map.getMaxZoom()
};
}
return formattedExtent;
}
get static() {
return this.hasAttribute('static');
}
set static(value) {
const isStatic = Boolean(value);
if (isStatic) this.setAttribute('static', '');
else this.removeAttribute('static');
}
constructor() {
// Always call super first in constructor
super();
this._source = this.outerHTML;
// create an array to track the history of the map and the current index
this._history = [];
this._historyIndex = -1;
this._traversalCall = false;
}
connectedCallback() {
this._initShadowRoot();
this._controlsList = new DOMTokenList(
this.getAttribute('controlslist'),
this,
'controlslist',
[
'noreload',
'nofullscreen',
'nozoom',
'nolayer',
'noscale',
'geolocation'
]
);
var s = window.getComputedStyle(this),
wpx = s.width,
hpx = s.height,
w = this.hasAttribute('width')
? this.getAttribute('width')
: parseInt(wpx.replace('px', '')),
h = this.hasAttribute('height')
? this.getAttribute('height')
: parseInt(hpx.replace('px', ''));
this._changeWidth(w);
this._changeHeight(h);
// wait for createmap event before creating leaflet map
// this allows a safeguard for the case where loading a custom TCRS takes
// longer than loading mapml-viewer.js/web-map.js
// the REASON we need a synchronous event listener (see comment below)
// is because the mapml-viewer element has / can have a size of 0 up until after
// something that happens between this point and the event handler executing
// perhaps a browser rendering cycle??
this.addEventListener('createmap', this._createMap);
let custom = !['CBMTILE', 'APSTILE', 'OSMTILE', 'WGS84'].includes(
this.projection
);
// this is worth a read, because dispatchEvent is synchronous
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
// In particular:
// "All applicable event handlers are called and return before dispatchEvent() returns."
if (!custom) {
this.dispatchEvent(new CustomEvent('createmap'));
}
// https://github.com/Maps4HTML/Web-Map-Custom-Element/issues/274
this.setAttribute('role', 'application');
this._toggleStatic();
/*
1. only deletes aria-label when the last (only remaining) map caption is removed
2. only deletes aria-label if the aria-label was defined by the map caption element itself
*/
let mapcaption = this.querySelector('map-caption');
if (mapcaption !== null) {
setTimeout(() => {
let ariaupdate = this.getAttribute('aria-label');
if (ariaupdate === mapcaption.innerHTML) {
this.mapCaptionObserver = new MutationObserver((m) => {
let mapcaptionupdate = this.querySelector('map-caption');
if (mapcaptionupdate !== mapcaption) {
this.removeAttribute('aria-label');
}
});
this.mapCaptionObserver.observe(this, {
childList: true
});
}
}, 0);
}
}
_initShadowRoot() {
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' });
}
let tmpl = document.createElement('template');
/* jshint ignore:start */
tmpl.innerHTML = `<link rel="stylesheet" href="${
new URL('mapml.css', import.meta.url).href
}">`;
/* jshint ignore:end */
let shadowRoot = this.shadowRoot;
this._container = document.createElement('div');
let output =
"<output role='status' aria-live='polite' aria-atomic='true' class='mapml-screen-reader-output'></output>";
this._container.insertAdjacentHTML('beforeend', output);
// Set default styles for the map element.
let mapDefaultCSS = document.createElement('style');
mapDefaultCSS.innerHTML =
`:host {` +
`all: initial;` + // Reset properties inheritable from html/body, as some inherited styles may cause unexpected issues with the map element's components (https://github.com/Maps4HTML/Web-Map-Custom-Element/issues/140).
`contain: layout size;` + // Contain layout and size calculations within the map element.
`display: inline-block;` + // This together with dimension properties is required so that Leaflet isn't working with a height=0 box by default.
`height: 150px;` + // Provide a "default object size" (https://github.com/Maps4HTML/HTML-Map-Element/issues/31).
`width: 300px;` +
`border-width: 2px;` + // Set a default border for contrast, similar to UA default for iframes.
`border-style: inset;` +
`}` +
`:host([frameborder="0"]) {` +
`border-width: 0;` +
`}` +
`:host([hidden]) {` +
`display: none!important;` +
`}` +
`:host .leaflet-control-container {` +
`visibility: hidden!important;` + // Visibility hack to improve percieved performance (mitigate FOUC) – visibility is unset in mapml.css! (https://github.com/Maps4HTML/Web-Map-Custom-Element/issues/154).
`}`;
// Hide all (light DOM) children of the map element.
let hideElementsCSS = document.createElement('style');
hideElementsCSS.innerHTML =
`mapml-viewer > * {` + `display: none!important;` + `}`;
this.appendChild(hideElementsCSS);
// Make the Leaflet container element programmatically identifiable
// (https://github.com/Leaflet/Leaflet/issues/7193).
this._container.setAttribute('role', 'region');
this._container.setAttribute('aria-label', 'Interactive map');
shadowRoot.appendChild(mapDefaultCSS);
shadowRoot.appendChild(tmpl.content.cloneNode(true));
shadowRoot.appendChild(this._container);
}
_createMap() {
if (!this._map) {
this._map = L.map(this._container, {
center: new L.LatLng(this.lat, this.lon),
projection: this.projection,
query: true,
contextMenu: true,
announceMovement: M.options.announceMovement,
featureIndex: true,
mapEl: this,
crs: M[this.projection],
zoom: this.zoom,
zoomControl: false,
// because the M.MapMLLayer invokes _tileLayer._onMoveEnd when
// the mapml response is received the screen tends to flash. I'm sure
// there is a better configuration than that, but at this moment
// I'm not sure how to approach that issue.
// See https://github.com/Maps4HTML/MapML-Leaflet-Client/issues/24
fadeAnimation: true
});
this._addToHistory();
this._createControls();
this._toggleControls();
this._crosshair = M.crosshair().addTo(this._map);
if (M.options.featureIndexOverlayOption)
this._featureIndexOverlay = M.featureIndexOverlay().addTo(this._map);
this._setUpEvents();
}
}
disconnectedCallback() {
while (this.shadowRoot.firstChild) {
this.shadowRoot.removeChild(this.shadowRoot.firstChild);
}
delete this._map;
this._deleteControls();
}
adoptedCallback() {
// console.log('Custom map element moved to new page.');
}
attributeChangedCallback(name, oldValue, newValue) {
// console.log('Attribute: ' + name + ' changed from: '+ oldValue + ' to: '+newValue);
// "Best practice": handle side-effects in this callback
// https://developers.google.com/web/fundamentals/web-components/best-practices
// https://developers.google.com/web/fundamentals/web-components/best-practices#avoid-reentrancy
// note that the example is misleading, since the user can't use
// setAttribute or removeAttribute to set the property, they need to use
// the property directly in their API usage, which kinda sucks
/*
const hasValue = newValue !== null;
switch (name) {
case 'checked':
// Note the attributeChangedCallback is only handling the *side effects*
// of setting the attribute.
this.setAttribute('aria-checked', hasValue);
break;
...
} */
switch (name) {
case 'controlslist':
if (this._controlsList) {
if (this._controlsList.valueSet === false) {
this._controlsList.value = newValue;
}
this._toggleControls();
}
break;
case 'controls':
if (oldValue !== null && newValue === null) {
this._hideControls();
} else if (oldValue === null && newValue !== null) {
this._showControls();
}
break;
case 'height':
if (oldValue !== newValue) {
this._changeHeight(newValue);
}
break;
case 'width':
if (oldValue !== newValue) {
this._changeWidth(newValue);
}
break;
case 'static':
this._toggleStatic();
break;
}
}
// Creates All map controls and adds them to the map, when created.
_createControls() {
let mapSize = this._map.getSize().y,
totalSize = 0;
this._layerControl = M.layerControl(null, {
collapsed: true,
mapEl: this
}).addTo(this._map);
let scaleValue = M.options.announceScale;
if (scaleValue === 'metric') {
scaleValue = { metric: true, imperial: false };
}
if (scaleValue === 'imperial') {
scaleValue = { metric: false, imperial: true };
}
if (!this._scaleBar)
this._scaleBar = M.scaleBar(scaleValue).addTo(this._map);
// Only add controls if there is enough top left vertical space
if (!this._zoomControl && totalSize + 93 <= mapSize) {
totalSize += 93;
this._zoomControl = L.control.zoom().addTo(this._map);
}
if (!this._reloadButton && totalSize + 49 <= mapSize) {
totalSize += 49;
this._reloadButton = M.reloadButton().addTo(this._map);
}
if (!this._fullScreenControl && totalSize + 49 <= mapSize) {
totalSize += 49;
this._fullScreenControl = M.fullscreenButton().addTo(this._map);
}
if (!this._geolocationButton) {
this._geolocationButton = M.geolocationButton().addTo(this._map);
}
}
// Sets controls by hiding/unhiding them based on the map attribute
_toggleControls() {
if (this.controls === false) {
this._hideControls();
this._map.contextMenu.toggleContextMenuItem('Controls', 'disabled');
} else {
this._showControls();
this._map.contextMenu.toggleContextMenuItem('Controls', 'enabled');
}
}
_hideControls() {
this._setControlsVisibility('fullscreen', true);
this._setControlsVisibility('layercontrol', true);
this._setControlsVisibility('reload', true);
this._setControlsVisibility('zoom', true);
this._setControlsVisibility('geolocation', true);
this._setControlsVisibility('scale', true);
}
_showControls() {
this._setControlsVisibility('fullscreen', false);
this._setControlsVisibility('layercontrol', false);
this._setControlsVisibility('reload', false);
this._setControlsVisibility('zoom', false);
this._setControlsVisibility('geolocation', true);
this._setControlsVisibility('scale', false);
// prune the controls shown if necessary
// this logic could be embedded in _showControls
// but would require being able to iterate the domain of supported tokens
// for the controlslist
if (this._controlsList) {
this._controlsList.forEach((value) => {
switch (value.toLowerCase()) {
case 'nofullscreen':
this._setControlsVisibility('fullscreen', true);
break;
case 'nolayer':
this._setControlsVisibility('layercontrol', true);
break;
case 'noreload':
this._setControlsVisibility('reload', true);
break;
case 'nozoom':
this._setControlsVisibility('zoom', true);
break;
case 'geolocation':
this._setControlsVisibility('geolocation', false);
break;
case 'noscale':
this._setControlsVisibility('scale', true);
break;
}
});
}
if (this._layerControl && this._layerControl._layers.length === 0) {
this._layerControl._container.setAttribute('hidden', '');
}
}
// delete the map controls that are private properties of this custom element
_deleteControls() {
delete this._layerControl;
delete this._zoomControl;
delete this._reloadButton;
delete this._fullScreenControl;
delete this._geolocationButton;
delete this._scaleBar;
}
// Sets the control's visibility AND all its childrens visibility,
// for the control element based on the Boolean hide parameter
_setControlsVisibility(control, hide) {
let container;
switch (control) {
case 'zoom':
if (this._zoomControl) {
container = this._zoomControl._container;
}
break;
case 'reload':
if (this._reloadButton) {
container = this._reloadButton._container;
}
break;
case 'fullscreen':
if (this._fullScreenControl) {
container = this._fullScreenControl._container;
}
break;
case 'layercontrol':
if (this._layerControl) {
container = this._layerControl._container;
}
break;
case 'geolocation':
if (this._geolocationButton) {
container = this._geolocationButton._container;
}
break;
case 'scale':
if (this._scaleBar) {
container = this._scaleBar._container;
}
break;
}
if (container) {
if (hide) {
// setting the visibility for all the children of the element
[...container.children].forEach((childEl) => {
childEl.setAttribute('hidden', '');
});
container.setAttribute('hidden', '');
} else {
// setting the visibility for all the children of the element
[...container.children].forEach((childEl) => {
childEl.removeAttribute('hidden');
});
container.removeAttribute('hidden');
}
}
}
_toggleStatic() {
const isStatic = this.hasAttribute('static');
if (this._map) {
if (isStatic) {
this._map.dragging.disable();
this._map.touchZoom.disable();
this._map.doubleClickZoom.disable();
this._map.scrollWheelZoom.disable();
this._map.boxZoom.disable();
this._map.keyboard.disable();
this._zoomControl.disable();
} else {
this._map.dragging.enable();
this._map.touchZoom.enable();
this._map.doubleClickZoom.enable();
this._map.scrollWheelZoom.enable();
this._map.boxZoom.enable();
this._map.keyboard.enable();
this._zoomControl.enable();
}
}
}
_dropHandler(event) {
event.preventDefault();
let text = event.dataTransfer.getData('text');
M._pasteLayer(this, text);
}
_dragoverHandler(event) {
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
}
_removeEvents() {
if (this._map) {
this._map.off();
this.removeEventListener('drop', this._dropHandler, false);
this.removeEventListener('dragover', this._dragoverHandler, false);
}
}
_setUpEvents() {
this.addEventListener('drop', this._dropHandler, false);
this.addEventListener('dragover', this._dragoverHandler, false);
this.addEventListener(
'change',
function (e) {
if (e.target.tagName === 'LAYER-') {
this.dispatchEvent(
new CustomEvent('layerchange', {
details: { target: this, originalEvent: e }
})
);
}
},
false
);
this.parentElement.addEventListener('keyup', function (e) {
if (
e.keyCode === 9 &&
document.activeElement.nodeName === 'MAPML-VIEWER'
) {
document.activeElement.dispatchEvent(
new CustomEvent('mapfocused', { detail: { target: this } })
);
}
});
// pasting layer-, links and geojson using Ctrl+V
this.addEventListener('keydown', function (e) {
if (e.keyCode === 86 && e.ctrlKey) {
navigator.clipboard.readText().then((layer) => {
M._pasteLayer(this, layer);
});
// Prevents default spacebar event on all of mapml-viewer
} else if (
e.keyCode === 32 &&
this.shadowRoot.activeElement.nodeName !== 'INPUT'
) {
e.preventDefault();
this._map.fire('keypress', { originalEvent: e });
}
});
this.parentElement.addEventListener('mousedown', function (e) {
if (document.activeElement.nodeName === 'MAPML-VIEWER') {
document.activeElement.dispatchEvent(
new CustomEvent('mapfocused', { detail: { target: this } })
);
}
});
this._map.on(
'locationfound',
function (e) {
this.dispatchEvent(
new CustomEvent('maplocationfound', {
detail: { latlng: e.latlng, accuracy: e.accuracy }
})
);
},
this
);
this._map.on(
'locationerror',
function (e) {
this.dispatchEvent(
new CustomEvent('locationerror', { detail: { error: e.message } })
);
},
this
);
this._map.on(
'load',
function () {
this.dispatchEvent(
new CustomEvent('load', { detail: { target: this } })
);
},
this
);
this._map.on(
'preclick',
function (e) {
this.dispatchEvent(
new CustomEvent('preclick', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'click',
function (e) {
this.dispatchEvent(
new CustomEvent('click', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'dblclick',
function (e) {
this.dispatchEvent(
new CustomEvent('dblclick', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'mousemove',
function (e) {
this.dispatchEvent(
new CustomEvent('mousemove', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'mouseover',
function (e) {
this.dispatchEvent(
new CustomEvent('mouseover', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'mouseout',
function (e) {
this.dispatchEvent(
new CustomEvent('mouseout', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'mousedown',
function (e) {
this.dispatchEvent(
new CustomEvent('mousedown', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'mouseup',
function (e) {
this.dispatchEvent(
new CustomEvent('mouseup', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'contextmenu',
function (e) {
this.dispatchEvent(
new CustomEvent('contextmenu', {
detail: {
lat: e.latlng.lat,
lon: e.latlng.lng,
x: e.containerPoint.x,
y: e.containerPoint.y
}
})
);
},
this
);
this._map.on(
'movestart',
function () {
this._updateMapCenter();
this.dispatchEvent(
new CustomEvent('movestart', { detail: { target: this } })
);
},
this
);
this._map.on(
'move',
function () {
this._updateMapCenter();
this.dispatchEvent(
new CustomEvent('move', { detail: { target: this } })
);
},
this
);
this._map.on(
'moveend',
function () {
this._updateMapCenter();
this._addToHistory();
this.dispatchEvent(
new CustomEvent('moveend', { detail: { target: this } })
);
},
this
);
this._map.on(
'zoomstart',
function () {
this._updateMapCenter();
this.dispatchEvent(
new CustomEvent('zoomstart', { detail: { target: this } })
);
},
this
);
this._map.on(
'zoom',
function () {
this._updateMapCenter();
this.dispatchEvent(
new CustomEvent('zoom', { detail: { target: this } })
);
},
this
);
this._map.on(
'zoomend',
function () {
this._updateMapCenter();
this.dispatchEvent(
new CustomEvent('zoomend', { detail: { target: this } })
);
},
this
);
this.addEventListener('fullscreenchange', function (event) {
if (document.fullscreenElement === null) {
// full-screen mode has been exited
this._map.contextMenu.setViewFullScreenInnerHTML('view');
} else {
this._map.contextMenu.setViewFullScreenInnerHTML('exit');
}
});
this.addEventListener('keydown', function (event) {
if (document.activeElement.nodeName === 'MAPML-VIEWER') {
// Check if Ctrl+R is pressed and map is focused
if (event.ctrlKey && event.keyCode === 82) {
// Prevent default browser behavior
event.preventDefault();
this.reload();
} else if (event.altKey && event.keyCode === 39) {
// Prevent default browser behavior
event.preventDefault();
this.forward();
} else if (event.altKey && event.keyCode === 37) {
// Prevent default browser behavior
event.preventDefault();
this.back();
}
}
});
}
locate(options) {
//options: https://leafletjs.com/reference.html#locate-options
if (this._geolocationButton) {
this._geolocationButton.stop();
}
if (options) {
if (options.zoomTo) {
options.setView = options.zoomTo;
delete options.zoomTo;
}
this._map.locate(options);
} else {
this._map.locate({ setView: true, maxZoom: 16 });
}
}
toggleDebug() {
if (this._debug) {
this._debug.remove();
this._debug = undefined;
} else {
this._debug = M.debugOverlay().addTo(this._map);
}
}
_changeWidth(width) {
if (this._container) {
this._container.style.width = width + 'px';
this.shadowRoot.styleSheets[0].cssRules[0].style.width = width + 'px';
}
if (this._map) {
this._map.invalidateSize(false);
}
}
_changeHeight(height) {
if (this._container) {
this._container.style.height = height + 'px';
this.shadowRoot.styleSheets[0].cssRules[0].style.height = height + 'px';
}
if (this._map) {
this._map.invalidateSize(false);
}
}
zoomTo(lat, lon, zoom) {
zoom = Number.isInteger(+zoom) ? +zoom : this.zoom;
let location = new L.LatLng(+lat, +lon);
this._map.setView(location, zoom);
this.zoom = zoom;
this.lat = location.lat;
this.lon = location.lng;
}
_updateMapCenter() {
// remember to tell Leaflet event handler that 'this' in here refers to
// something other than the map in this case the custom polymer element
this.lat = this._map.getCenter().lat;
this.lon = this._map.getCenter().lng;
this.zoom = this._map.getZoom();
}
/**
* Adds to the maps history on moveends
* @private
*/
_addToHistory() {
if (this._traversalCall > 0) {
// this._traversalCall tracks how many consecutive moveends to ignore from history
this._traversalCall--; // this is useful for ignoring moveends corresponding to back, forward and reload
return;
}
let mapLocation = this._map.getPixelBounds().getCenter();
let location = {
zoom: this._map.getZoom(),
x: mapLocation.x,
y: mapLocation.y
};
this._historyIndex++;
this._history.splice(this._historyIndex, 0, location);
// Remove future history and overwrite it when map pan/zoom while inside history
if (this._historyIndex + 1 !== this._history.length) {
this._history.length = this._historyIndex + 1;
}
if (this._historyIndex === 0) {
// when at initial state of map, disable back, forward, and reload items
this._map.contextMenu.toggleContextMenuItem('Back', 'disabled'); // back contextmenu item
this._map.contextMenu.toggleContextMenuItem('Forward', 'disabled'); // forward contextmenu item
this._map.contextMenu.toggleContextMenuItem('Reload', 'disabled'); // reload contextmenu item
this._reloadButton?.disable();
} else {
this._map.contextMenu.toggleContextMenuItem('Back', 'enabled'); // back contextmenu item
this._map.contextMenu.toggleContextMenuItem('Forward', 'disabled'); // forward contextmenu item
this._map.contextMenu.toggleContextMenuItem('Reload', 'enabled'); // reload contextmenu item
this._reloadButton?.enable();
}
}
/**
* Allow user to move back in history
*/
back() {
let history = this._history;
let curr = history[this._historyIndex];
if (this._historyIndex > 0) {
this._map.contextMenu.toggleContextMenuItem('Forward', 'enabled'); // forward contextmenu item
this._historyIndex--;
let prev = history[this._historyIndex];
// Disable back, reload contextmenu item when at the end of history
if (this._historyIndex === 0) {
this._map.contextMenu.toggleContextMenuItem('Back', 'disabled'); // back contextmenu item
this._map.contextMenu.toggleContextMenuItem('Reload', 'disabled'); // reload contextmenu item
this._reloadButton?.disable();
}
if (prev.zoom !== curr.zoom) {
this._traversalCall = 2; // allows the next 2 moveends to be ignored from history
let currScale = this._map.options.crs.scale(curr.zoom); // gets the scale of the current zoom level
let prevScale = this._map.options.crs.scale(prev.zoom); // gets the scale of the previous zoom level
let scale = currScale / prevScale; // used to convert the previous pixel location to be in terms of the current zoom level