-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathweb-map.js
More file actions
568 lines (541 loc) · 19.9 KB
/
Copy pathweb-map.js
File metadata and controls
568 lines (541 loc) · 19.9 KB
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
import './leaflet-src.js'; // a lightly modified version of Leaflet for use as browser module
import './proj4-src.js'; // modified version of proj4; could be stripped down for mapml
import './proj4leaflet.js'; // not modified, seems to adapt proj4 for leaflet use.
import './mapml.js'; // refactored URI usage, replaced with URL standard
import './Leaflet.fullscreen.js';
import { MapLayer } from './layer.js';
import { MapArea } from './map-area.js';
export class WebMap extends HTMLMapElement {
static get observedAttributes() {
return ['lat', 'lon', 'zoom', 'projection', 'width', 'height', 'controls'];
}
// 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');
this._toggleControls(hasControls);
}
get controlslist() {
return this.hasAttribute('controlslist') ? this.getAttribute("controlslist") : "";
}
set controlslist(val) {
if (val.toLowerCase() === "nofullscreen") {
this.setAttribute("controlslist", "nofullscreen");
}
}
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") : "OSMTILE";
}
set projection(val) {
if (val && (val === "OSMTILE" || val === "CBMTILE" || val === "APSTILE" || val === "WGS84")) {
this.setAttribute('projection', val);
}
}
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 areas() {
return this.getElementsByTagName('area');
}
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);
}
constructor() {
// Always call super first in constructor
super();
this._source = this.outerHTML;
let tmpl = document.createElement('template');
tmpl.innerHTML =
`<link rel="stylesheet" href="${new URL("leaflet.css", import.meta.url).href}">` +
`<link rel="stylesheet" href="${new URL("leaflet.fullscreen.css", import.meta.url).href}">` +
`<link rel="stylesheet" href="${new URL("mapml.css", import.meta.url).href}">`;
const rootDiv = document.createElement('div');
rootDiv.classList.add('web-map');
let shadowRoot = rootDiv.attachShadow({mode: 'open'});
this._container = document.createElement('div');
// Set default styles for the map element.
let mapDefaultCSS = document.createElement('style');
mapDefaultCSS.innerHTML =
`map[is="web-map"] {` +
`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: content;` + // Contain layout and paint 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.
`overflow: hidden;` + // Make the map element behave and look more like a native element.
`height: 150px;` + // Provide a "default object size" (https://github.com/Maps4HTML/HTML-Map-Element/issues/31).
`width: 300px;` +
`border-width: 2px;` +
`border-style: inset;` +
`}` +
`map[is="web-map"] .web-map {` +
`display: contents;` + // This div doesn't have to participate in layout by generating its own box.
`}`;
// Hide all (light DOM) children of the map element except for the
// `<area>` and `<div class="web-map">` (shadow root host) elements.
let hideElementsCSS = document.createElement('style');
hideElementsCSS.innerHTML =
`map[is="web-map"] > :not(area):not(.web-map) {` +
`display: none!important;` +
`}`;
shadowRoot.appendChild(tmpl.content.cloneNode(true));
shadowRoot.appendChild(this._container);
this.appendChild(rootDiv);
this.appendChild(hideElementsCSS);
document.head.insertAdjacentElement('afterbegin', mapDefaultCSS);
}
connectedCallback() {
if (this.isConnected) {
// the dimension attributes win, if they're there. A map does not
// have an intrinsic size, unlike an image or video, and so must
// have a defined width and height.
var s = window.getComputedStyle(this),
wpx = s.width, hpx=s.height,
w = parseInt(wpx.replace('px','')),
h = parseInt(hpx.replace('px',''));
if (wpx === "" || hpx === "") {
return;
}
if (!this.width || this.width !== w) {
this._container.style.width = wpx;
this.width = w;
} else {
this._container.style.width = this.width+"px";
}
if (!this.height || this.height !== h) {
this._container.style.height = hpx;
this.height = h;
} else {
this._container.style.height = this.height+"px";
}
// create an array to track the history of the map and the current index
if(!this._history){
this._history = [];
this._historyIndex = -1;
this._traversalCall = false;
}
// create the Leaflet map if this is the first time attached is called
if (!this._map) {
this._map = L.map(this._container, {
center: new L.LatLng(this.lat, this.lon),
projection: this.projection,
query: true,
contextMenu: 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
});
// the attribution control is not optional
this._attributionControl = this._map.attributionControl.setPrefix('<a href="https://www.w3.org/community/maps4html/" title="W3C Maps4HTML Community Group">Maps4HTML</a> | <a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>');
// optionally add controls to the map
if (this.controls) {
this._layerControl = M.mapMlLayerControl(null,{"collapsed": true}).addTo(this._map);
this._zoomControl = L.control.zoom().addTo(this._map);
if (!this.controlslist.toLowerCase().includes("nofullscreen")) {
this._fullScreenControl = L.control.fullscreen().addTo(this._map);
}
}
if (this.hasAttribute('name')) {
var name = this.getAttribute('name');
if (name) {
this.poster = document.querySelector('img[usemap='+'"#'+name+'"]');
// firefox has an issue where the attribution control's use of
// _container.innerHTML does not work properly if the engine is throwing
// exceptions because there are no area element children of the image map
// for firefox only, a workaround is to actually remove the image...
if (this.poster) {
if (L.Browser.gecko) {
this.poster.removeAttribute('usemap');
}
//this.appendChild(this.poster);
}
}
}
// undisplay the img in the image map, because it's not needed now
// gives a slight fouc, not optimal
if (this.poster) {
this.poster.style.display = 'none';
}
this._setUpEvents();
// this.fire('load', {target: this});
}
}
}
disconnectedCallback() {
//this._removeEvents();
delete this._map;
}
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;
...
} */
}
_dropHandler(event) {
event.preventDefault();
// create a new <layer-> child of this <map> element
let l = new MapLayer();
l.src = event.dataTransfer.getData("text");
l.label = 'Layer';
l.checked = 'true';
this.appendChild(l);
l.addEventListener("error", function () {
if (l.parentElement) {
// should invoke lifecyle callbacks automatically by removing it from DOM
l.parentElement.removeChild(l);
}
// garbage collect it
l = null;
});
}
_dragoverHandler(event) {
function contains(list, value) {
for( var i = 0; i < list.length; ++i ) {
if(list[i] === value) return true;
}
return false;
}
// check if the thing being dragged is a URL
var isLink = contains( event.dataTransfer.types, "text/uri-list");
if (isLink) {
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
}
}
_removeEvents() {
if (this._map) {
this._map.off('preclick click dblclick mousemove mouseover mouseout mousedown mouseup contextmenu', false, this);
this._map.off('load movestart move moveend zoomstart zoom zoomend', false, this);
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._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);
}
_toggleControls(controls) {
if (this._map) {
if (controls && !this._layerControl) {
this._zoomControl = L.control.zoom().addTo(this._map);
this._layerControl = M.mapMlLayerControl(null,{"collapsed": true}).addTo(this._map);
if (!this.controlslist.toLowerCase().includes("nofullscreen")) {
this._fullScreenControl = L.control.fullscreen().addTo(this._map);
}
for (var i=0;i<this.layers.length;i++) {
if (!this.layers[i].hidden) {
this._layerControl.addOverlay(this.layers[i]._layer, this.layers[i].label);
this._map.on('moveend', this.layers[i]._validateDisabled, this.layers[i]);
this.layers[i]._layerControl = this._layerControl;
}
}
} else if (this._layerControl) {
this._map.removeControl(this._layerControl);
this._map.removeControl(this._zoomControl);
if (this._fullScreenControl) {
this._map.removeControl(this._fullScreenControl);
delete this._fullScreenControl;
}
delete this._layerControl;
delete this._zoomControl;
}
}
}
toggleDebug(){
let mapEl = this;
if(mapEl._debug){
this._debug.remove();
this._debug = undefined;
} else {
this._debug = M.debugOverlay().addTo(this._map);
}
}
_widthChanged(width) {
this.style.width = width+"px";
this._container.style.width = width+"px";
if (this._map) {
this._map.invalidateSize(false);
}
}
_heightChanged(height) {
this.style.height = height+"px";
this._container.style.height = height+"px";
if (this._map) {
this._map.invalidateSize(false);
}
}
zoomTo(lat, lon, zoom) {
zoom = Number.isInteger(zoom)? zoom:this.zoom;
var 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();
}
_addToHistory(){
if(this._traversalCall){
this._traversalCall = false;
return;
}
let mapLocation = this._map.getCenter();
let location ={
zoom:this._map.getZoom(),
lat:mapLocation.lat,
lng:mapLocation.lng,
};
this._historyIndex++;
this._history.push(location);
}
back(){
let mapEl = this,
history = mapEl._history;
if(mapEl._historyIndex > 0){
mapEl._historyIndex--;
}
let prev = history[mapEl._historyIndex];
mapEl._traversalCall = true;
mapEl.zoomTo(prev.lat,prev.lng,prev.zoom);
}
forward(){
let mapEl = this,
history = this._history;
if(mapEl._historyIndex < history.length -1){
mapEl._historyIndex++;
}
let next = history[this._historyIndex];
mapEl._traversalCall = true;
mapEl.zoomTo(next.lat,next.lng,next.zoom);
}
reload(){
let mapEl = this,
initialLocation = mapEl._history.shift();
mapEl._history = [initialLocation];
mapEl._historyIndex = -1;
mapEl._traversalCall = true;
mapEl.zoomTo(initialLocation.lat,initialLocation.lng,initialLocation.zoom);
}
viewSource(){
let blob = new Blob([this._source],{type:"text/plain"}),
url = URL.createObjectURL(blob);
window.open(url);
URL.revokeObjectURL(url);
}
_ready() {
// when used in a custom element, the leaflet script element is hidden inside
// the import's shadow dom.
// this might not work and may not be necessary in standard custom elements
L.Icon.Default.imagePath = (function () {
var imp = document.querySelector('link[rel="import"][href*="web-map.html"]'),
doc = imp ? imp.import : document,
scripts = doc.getElementsByTagName('script'),
leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
var i, len, src, path;
for (i = 0, len = scripts.length; i < len; i++) {
src = scripts[i].src;
if (src.match(leafletRe)) {
path = src.split(leafletRe)[0];
return (path ? path + '/' : '') + 'images';
}
}
}());
if (this.hasAttribute('name')) {
var name = this.getAttribute('name');
if (name) {
this.poster = document.querySelector('img[usemap='+'"#'+name+'"]');
// firefox has an issue where the attribution control's use of
// _container.innerHTML does not work properly if the engine is throwing
// exceptions because there are no area element children of the image map
// for firefox only, a workaround is to actually remove the image...
if (this.poster) {
if (L.Browser.gecko) {
this.poster.removeAttribute('usemap');
}
this._container.appendChild(this.poster);
}
}
}
}
}
// need to provide options { extends: ... } for custom built-in elements
window.customElements.define('web-map', WebMap, { extends: 'map' });
window.customElements.define('layer-', MapLayer);
window.customElements.define('map-area', MapArea, {extends: 'area'});