forked from Maps4HTML/MapML.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap-feature.js
648 lines (615 loc) · 23.7 KB
/
map-feature.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
export class MapFeature extends HTMLElement {
static get observedAttributes() {
return ['zoom', 'min', 'max'];
}
get zoom() {
return +(this.hasAttribute('zoom') ? this.getAttribute('zoom') : 0);
}
set zoom(val) {
var parsedVal = parseInt(val, 10);
if (!isNaN(parsedVal) && parsedVal >= this.min && parsedVal <= this.max) {
this.setAttribute('zoom', parsedVal);
}
}
get min() {
// fallback: the minimum zoom bound of layer- element
return +(this.hasAttribute('min')
? this.getAttribute('min')
: this._layer._layerEl.extent.zoom.minZoom);
}
set min(val) {
var parsedVal = parseInt(val, 10);
if (!isNaN(parsedVal)) {
if (
parsedVal >= this._layer._layerEl.extent.zoom.minZoom &&
parsedVal <= this._layer._layerEl.extent.zoom.maxZoom
) {
this.setAttribute('min', parsedVal);
} else {
this.setAttribute('min', this._layer._layerEl.extent.zoom.minZoom);
}
}
}
get max() {
// fallback: the maximum zoom bound of layer- element
return +(this.hasAttribute('max')
? this.getAttribute('max')
: this._layer._layerEl.extent.zoom.maxZoom);
}
set max(val) {
var parsedVal = parseInt(val, 10);
if (!isNaN(parsedVal)) {
if (
parsedVal >= this._layer._layerEl.extent.zoom.minZoom &&
parsedVal <= this._layer._layerEl.extent.zoom.maxZoom
) {
this.setAttribute('max', parsedVal);
} else {
this.setAttribute('max', this._layer._layerEl.extent.zoom.maxZoom);
}
}
}
get extent() {
if (this.isConnected) {
// if the feature extent is the first time to be calculated or the feature extent is changed (by changing
// the innertext of map-coordinates), then calculate feature extent by invoking the getFeatureExtent function
if (!this._getFeatureExtent) {
this._getFeatureExtent = this._memoizeExtent();
}
return this._getFeatureExtent();
}
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'zoom': {
if (oldValue !== newValue && this._layer) {
let layer = this._layer,
layerEl = layer._layerEl,
mapmlvectors = layer._mapmlvectors;
// if the vector layer only has static features, should update zoom bounds when zoom attribute is changed
if (mapmlvectors?._staticFeature) {
this._removeInFeatureList(oldValue);
let native = this._getNativeZoomAndCS(layer._content);
mapmlvectors.zoomBounds = mapmlvectors._getZoomBounds(
layerEl.shadowRoot || layerEl,
native.zoom
);
}
this._removeFeature();
this._updateFeature();
}
break;
}
}
}
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
// if mapFeature element is not connected to layer- or layer-'s shadowroot,
// or the parent layer- element has a "data-moving" attribute
if (
(this.parentNode.nodeType !== document.DOCUMENT_FRAGMENT_NODE &&
this.parentNode.nodeName.toLowerCase() !== 'layer-') ||
(this.parentNode.nodeType === document.DOCUMENT_FRAGMENT_NODE &&
this.parentNode.host.hasAttribute('data-moving')) ||
(this.parentNode.nodeName.toLowerCase() === 'layer-' &&
this.parentNode.hasAttribute('data-moving'))
) {
return;
}
// set up the map-feature object properties
this._addFeature();
// use observer to monitor the changes in mapFeature's subtree
// (i.e. map-properties, map-featurecaption, map-coordinates)
this._observer = new MutationObserver((mutationList) => {
for (let mutation of mutationList) {
// the attributes changes of <map-feature> element should be handled by attributeChangedCallback()
if (mutation.type === 'attributes' && mutation.target === this) {
return;
}
// re-render feature if there is any observed change
this._removeFeature();
this._updateFeature();
}
});
this._observer.observe(this, {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: true,
characterData: true
});
}
disconnectedCallback() {
if (this._layer._layerEl.hasAttribute('data-moving')) return;
this._removeFeature();
this._observer.disconnect();
}
_removeFeature() {
// if the <layer- > el is disconnected
// the <g> el has already got removed at this point
if (this._groupEl?.isConnected) {
this._groupEl.remove();
}
// if the <layer- > el has already been disconnected,
// then _map.removeLayer(layerEl._layer) has already been invoked (inside layerEl.disconnectedCallback())
// this._featureGroup has already got removed at this point
if (this._featureGroup?._map) {
this._featureGroup._map.removeLayer(this._featureGroup);
let mapmlvectors = this._layer._mapmlvectors;
if (mapmlvectors) {
if (mapmlvectors._staticFeature) {
if (mapmlvectors._features[this.zoom]) {
this._removeInFeatureList(this.zoom);
}
let container = this._layer.shadowRoot || this._layer._layerEl;
// update zoom bounds of vector layer
mapmlvectors.zoomBounds = mapmlvectors._getZoomBounds(
container,
this._getNativeZoomAndCS(this._layer._content).zoom
);
}
mapmlvectors.options.properties = null;
delete mapmlvectors._layers[this._featureGroup._leaflet_id];
}
}
delete this._featureGroup;
delete this._groupEl;
// ensure that feature extent can be re-calculated everytime that map-feature element is updated / re-added
if (this._getFeatureExtent) delete this._getFeatureExtent;
}
_addFeature() {
this._parentEl =
this.parentNode.nodeName.toUpperCase() === 'LAYER-' ||
this.parentNode.nodeName.toUpperCase() === 'MAP-EXTENT'
? this.parentNode
: this.parentNode.host;
// arrow function is not hoisted, define before use
var _attachedToMap = (e) => {
if (!this._parentEl._layer._map) {
// if the parent layer- el has not yet added to the map (i.e. not yet rendered), wait until it is added
this._layer.once(
'attached',
function () {
this._map = this._layer._map;
},
this
);
} else {
this._map = this._layer._map;
}
// "synchronize" the event handlers between map-feature and <g>
if (!this.querySelector('map-geometry')) return;
if (!this._layer._mapmlvectors) {
// if vector layer has not yet created (i.e. the layer- is not yet rendered on the map / layer is empty)
let layerEl = this._layer._layerEl;
this._layer.once('add', this._setUpEvents, this);
if (
!layerEl.querySelector('map-extent, map-tile') &&
!layerEl.hasAttribute('src') &&
layerEl.querySelectorAll('map-feature').length === 1
) {
// if the map-feature is added to an empty layer, fire extentload to create vector layer
// must re-run _initialize of MapMLLayer.js to re-set layer._extent (layer._extent is null for an empty layer)
this._layer._initialize(layerEl);
this._layer.fire('extentload');
}
return;
} else if (!this._featureGroup) {
// if the map-feature el or its subtree is updated
// this._featureGroup has been free in this._removeFeature()
this._updateFeature();
} else {
this._setUpEvents();
}
};
if (!this._parentEl._layer) {
// for custom projection cases, the MapMLLayer has not yet created and binded with the layer- at this point,
// because the "createMap" event of mapml-viewer has not yet been dispatched, the map has not yet been created
// the event will be dispatched after defineCustomProjection > projection setter
// should wait until MapMLLayer is built
let parentLayer =
this._parentEl.nodeName.toUpperCase() === 'LAYER-'
? this._parentEl
: this._parentEl.parentElement || this._parentEl.parentNode.host;
parentLayer.parentNode.addEventListener('createmap', (e) => {
this._layer = parentLayer._layer;
_attachedToMap();
});
} else {
this._layer = this._parentEl._layer;
_attachedToMap();
}
}
_updateFeature() {
let mapmlvectors = this._layer._mapmlvectors;
// if the parent layer has not yet rendered on the map
if (!mapmlvectors) return;
// if the <layer- > is not removed, then regenerate featureGroup and update the mapmlvectors accordingly
let native = this._getNativeZoomAndCS(this._layer._content);
this._featureGroup = mapmlvectors.addData(this, native.cs, native.zoom);
mapmlvectors._layers[this._featureGroup._leaflet_id] = this._featureGroup;
this._groupEl = this._featureGroup.options.group;
if (mapmlvectors._staticFeature) {
let container = this._layer.shadowRoot || this._layer._layerEl;
// update zoom bounds of vector layer
mapmlvectors.zoomBounds = mapmlvectors._getZoomBounds(
container,
this._getNativeZoomAndCS(this._layer._content).zoom
);
// add feature layers to map
mapmlvectors._resetFeatures();
// update map's zoom limit
this._map._addZoomLimit(mapmlvectors);
L.extend(mapmlvectors.options, mapmlvectors.zoomBounds);
}
this._setUpEvents();
}
_setUpEvents() {
['click', 'focus', 'blur', 'keyup', 'keydown'].forEach((name) => {
// when <g> is clicked / focused / blurred
// should dispatch the click / focus / blur event listener on **linked HTMLFeatureElements**
this._groupEl.addEventListener(name, (e) => {
if (name === 'click') {
// dispatch a cloned mouseevent to trigger the click event handlers set on HTMLFeatureElement
let clickEv = new PointerEvent(name, { cancelable: true });
clickEv.originalEvent = e;
this.dispatchEvent(clickEv);
} else if (name === 'keyup' || name === 'keydown') {
let keyEv = new KeyboardEvent(name, { cancelable: true });
keyEv.originalEvent = e;
this.dispatchEvent(keyEv);
} else {
// dispatch a cloned focusevent to trigger the focus/blue event handlers set on HTMLFeatureElement
let focusEv = new FocusEvent(name, { cancelable: true });
focusEv.originalEvent = e;
this.dispatchEvent(focusEv);
}
});
});
}
_getNativeZoomAndCS(content) {
// content: referred to <layer- > if the <layer- > has inline <map-extent>, <map-feature> or <map-tile>
// referred to remote mapml if the <layer- > has a src attribute, and the fetched mapml contains <map-feature>
// referred to [map-meta, ...] if it is query
// referred to null otherwise (i.e. <layer- > has fetched <map-extent> in shadow, the <map-feature> attaches to <map-extent>'s shadow)
let nativeZoom, nativeCS;
if (this._extentEl) {
// feature attaches to extent's shadow
if (this._extentEl.querySelector('map-link[rel=query]')) {
// for query, fallback zoom is the current map zoom level that the query is returned
let metaZoom, metaCS;
if (content) {
metaZoom = M._metaContentToObject(
Array.prototype.filter
.call(content, function (elem) {
return elem.matches('map-meta[name=zoom]');
})[0]
?.getAttribute('content')
).content;
metaCS = M._metaContentToObject(
Array.prototype.filter
.call(content, function (elem) {
return elem.matches('map-meta[name=cs]');
})[0]
?.getAttribute('content')
).content;
}
nativeZoom = metaZoom || this._map.getZoom();
nativeCS = metaCS || 'gcrs';
} else if (this._extentEl.querySelector('map-link[rel=features]')) {
// for templated feature, read fallback from the fetched mapml's map-meta[name=zoom / cs]
nativeZoom = this._extentEl._nativeZoom;
nativeCS = this._extentEl._nativeCS;
}
return { zoom: nativeZoom, cs: nativeCS };
} else {
// feature attaches to layer- or layer-'s shadow
if (content.nodeType === Node.DOCUMENT_NODE) {
// for features migrated from mapml, read native zoom and cs from the remote mapml
return this._layer._mapmlvectors._getNativeVariables(content);
} else if (content.nodeName.toUpperCase() === 'LAYER-') {
// for inline features, read native zoom and cs from inline map-meta
let zoomMeta = this._parentEl.querySelectorAll('map-meta[name=zoom]'),
zoomLength = zoomMeta?.length;
nativeZoom = zoomLength
? +zoomMeta[zoomLength - 1]
.getAttribute('content')
?.split(',')
.find((str) => str.includes('value'))
?.split('=')[1]
: 0;
let csMeta = this._parentEl.querySelectorAll('map-meta[name=cs]'),
csLength = csMeta?.length;
nativeCS = csLength
? csMeta[csLength - 1].getAttribute('content')
: 'gcrs';
return { zoom: nativeZoom, cs: nativeCS };
}
}
}
// Util functions:
// internal method to calculate the extent of the feature and store it in cache for the first time
// and return cache when feature's extent is repeatedly requested
// for .extent
_memoizeExtent() {
// memoize calculated extent
let extentCache;
return function () {
if (extentCache && this._getFeatureExtent) {
// if the extent has already been calculated and is not updated, return stored extent
return extentCache;
} else {
// calculate feature extent
let map = this._map,
geometry = this.querySelector('map-geometry'),
native = this._getNativeZoomAndCS(
this._layer._content || this._layer.metas
),
cs = geometry.getAttribute('cs') || native.cs,
// zoom level that the feature rendered at
zoom = this.zoom || native.zoom,
shapes = geometry.querySelectorAll(
'map-point, map-linestring, map-polygon, map-multipoint, map-multilinestring'
),
bboxExtent = [
Infinity,
Infinity,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
];
for (let shape of shapes) {
let coord = shape.querySelectorAll('map-coordinates');
for (let i = 0; i < coord.length; ++i) {
bboxExtent = _updateExtent(shape, coord[i], bboxExtent);
}
}
let topLeft = L.point(bboxExtent[0], bboxExtent[1]);
let bottomRight = L.point(bboxExtent[2], bboxExtent[3]);
let pcrsBound = M.boundsToPCRSBounds(
L.bounds(topLeft, bottomRight),
zoom,
map.options.projection,
cs
);
if (
shapes.length === 1 &&
shapes[0].tagName.toUpperCase() === 'MAP-POINT'
) {
let projection = map.options.projection,
maxZoom = this.hasAttribute('max')
? +this.getAttribute('max')
: M[projection].options.resolutions.length - 1,
tileCenter = M[projection].options.crs.tile.bounds.getCenter(),
pixel = M[projection].transformation.transform(
pcrsBound.min,
M[projection].scale(+this.zoom || maxZoom)
);
pcrsBound = M.pixelToPCRSBounds(
L.bounds(pixel.subtract(tileCenter), pixel.add(tileCenter)),
this.zoom || maxZoom,
projection
);
}
let result = M._convertAndFormatPCRS(pcrsBound, map);
// memoize calculated result
extentCache = result;
return result;
}
};
// update the bboxExtent
function _updateExtent(shape, coord, bboxExtent) {
let data = coord.innerHTML
.trim()
.replace(/<[^>]+>/g, '')
.replace(/\s+/g, ' ')
.split(/[<>\ ]/g);
switch (shape.tagName) {
case 'MAP-POINT':
bboxExtent = M._updateExtent(bboxExtent, +data[0], +data[1]);
break;
case 'MAP-LINESTRING':
case 'MAP-POLYGON':
case 'MAP-MULTIPOINT':
case 'MAP-MULTILINESTRING':
for (let i = 0; i < data.length; i += 2) {
bboxExtent = M._updateExtent(bboxExtent, +data[i], +data[i + 1]);
}
break;
default:
break;
}
return bboxExtent;
}
}
// find and remove the feature from mapmlvectors._features if vector layer only contains static features, helper function
// prevent it from being rendered again when zooming in / out (mapmlvectors.resetFeature() is invoked)
_removeInFeatureList(zoom) {
let mapmlvectors = this._layer._mapmlvectors;
for (let i = 0; i < mapmlvectors._features[zoom].length; ++i) {
let feature = mapmlvectors._features[zoom][i];
if (feature._leaflet_id === this._featureGroup._leaflet_id) {
mapmlvectors._features[zoom].splice(i, 1);
break;
}
}
}
getMaxZoom() {
let tL = this.extent.topLeft.pcrs,
bR = this.extent.bottomRight.pcrs,
bound = L.bounds(
L.point(tL.horizontal, tL.vertical),
L.point(bR.horizontal, bR.vertical)
);
let projection = this._map.options.projection,
layerZoomBounds = this._layer._layerEl.extent.zoom,
minZoom = layerZoomBounds.minZoom ? layerZoomBounds.minZoom : 0,
maxZoom = layerZoomBounds.maxZoom
? layerZoomBounds.maxZoom
: M[projection].options.resolutions.length - 1;
let newZoom;
if (this.hasAttribute('zoom')) {
// if there is a zoom attribute set to the map-feature, zoom to the zoom attribute value
newZoom = this.zoom;
} else {
// if not, calculate the maximum zoom level that can show the feature completely
newZoom = M.getMaxZoom(bound, this._map, minZoom, maxZoom);
if (this.max < newZoom) {
// if the calculated zoom is greater than the value of max zoom attribute, go with max zoom attribute
newZoom = this.max;
} else if (this.min > newZoom) {
// if the calculated zoom is less than the value of min zoom attribute, go with min zoom attribute
newZoom = this.min;
}
}
// prevent overzooming / underzooming
if (newZoom < minZoom) {
newZoom = minZoom;
} else if (newZoom > maxZoom) {
newZoom = maxZoom;
}
// should check whether the extent after zooming falls into the templated extent bound
return newZoom;
}
// internal support for returning a GeoJSON representation of <map-feature> geometry
// The options object can contain the following:
// propertyFunction - function(<map-properties>), A function that maps the features' <map-properties> element to a GeoJSON "properties" member.
// transform - Bool, Transform coordinates to gcrs values, defaults to True
// mapml2geojson: <map-feature> Object -> GeoJSON
mapml2geojson(options) {
let defaults = {
propertyFunction: null,
transform: true
};
// assign default values for undefined options
options = Object.assign({}, defaults, options);
let json = {
type: 'Feature',
properties: {},
geometry: {}
};
let el = this.querySelector('map-properties');
if (!el) {
json.properties = null;
} else if (typeof options.propertyFunction === 'function') {
json.properties = options.propertyFunction(el);
} else if (el.querySelector('table')) {
// setting properties when table presented
let table = el.querySelector('table').cloneNode(true);
json.properties = M._table2properties(table);
} else {
// when no table present, strip any possible html tags to only get text
json.properties = {
prop0: el.innerHTML.replace(/(<([^>]+)>)/gi, '').replace(/\s/g, '')
};
}
// transform to gcrs if options.transform = true (default)
let source = null,
dest = null;
if (options.transform) {
source = new proj4.Proj(this._map.options.crs.code);
dest = new proj4.Proj('EPSG:4326');
if (
this._map.options.crs.code === 'EPSG:3857' ||
this._map.options.crs.code === 'EPSG:4326'
) {
options.transform = false;
}
}
let collection = this.querySelector('map-geometry').querySelector(
'map-geometrycollection'
),
shapes = this.querySelector('map-geometry').querySelectorAll(
'map-point, map-polygon, map-linestring, map-multipoint, map-multipolygon, map-multilinestring'
);
if (collection) {
json.geometry.type = 'GeometryCollection';
json.geometry.geometries = [];
for (let shape of shapes) {
json.geometry.geometries.push(
M._geometry2geojson(shape, source, dest, options.transform)
);
}
} else {
json.geometry = M._geometry2geojson(
shapes[0],
source,
dest,
options.transform
);
}
return json;
}
// a method that simulates a click, or invoking the user-defined click event
click() {
let g = this._groupEl,
rect = g.getBoundingClientRect();
let event = new MouseEvent('click', {
clientX: rect.x + rect.width / 2,
clientY: rect.y + rect.height / 2,
button: 0
});
let properties = this.querySelector('map-properties');
if (g.getAttribute('role') === 'link') {
for (let path of g.children) {
path.mousedown.call(this._featureGroup, event);
path.mouseup.call(this._featureGroup, event);
}
}
// dispatch click event for map-feature to allow events entered by 'addEventListener'
let clickEv = new PointerEvent('click', { cancelable: true });
clickEv.originalEvent = event;
this.dispatchEvent(clickEv);
// for custom projection, layer- element may disconnect and re-attach to the map after the click
// so check whether map-feature element is still connected before any further operations
if (properties && this.isConnected) {
let featureGroup = this._featureGroup,
shapes = featureGroup._layers;
// close popup if the popup is currently open
for (let id in shapes) {
if (shapes[id].isPopupOpen()) {
shapes[id].closePopup();
}
}
if (featureGroup.isPopupOpen()) {
featureGroup.closePopup();
} else if (!clickEv.originalEvent.cancelBubble) {
// If stopPropagation is not set on originalEvent by user
featureGroup.openPopup();
}
}
}
// a method that sets the current focus to the <g> element, or invoking the user-defined focus event
// options (optional): as options parameter for native HTMLElement
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
focus(options) {
this._groupEl.focus(options);
}
// a method that makes the <g> element lose focus, or invoking the user-defined blur event
blur() {
if (
document.activeElement.shadowRoot?.activeElement === this._groupEl ||
document.activeElement.shadowRoot?.activeElement.parentNode ===
this._groupEl
) {
this._groupEl.blur();
// set focus to the map container
this._map._container.focus();
}
}
// a method that can the viewport to be centred on the feature's extent
zoomTo() {
let extent = this.extent,
map = this._map;
let tL = extent.topLeft.pcrs,
bR = extent.bottomRight.pcrs,
bound = L.bounds(
L.point(tL.horizontal, tL.vertical),
L.point(bR.horizontal, bR.vertical)
),
center = map.options.crs.unproject(bound.getCenter(true));
map.setView(center, this.getMaxZoom(), { animate: false });
}
}