forked from Maps4HTML/MapML.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeatureLayer.js
537 lines (509 loc) · 17.2 KB
/
FeatureLayer.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
import { FALLBACK_CS, FALLBACK_PROJECTION } from '../utils/Constants';
export var FeatureLayer = L.FeatureGroup.extend({
/*
* M.MapML turns any MapML feature data into a Leaflet layer. Based on L.GeoJSON.
*/
initialize: function (mapml, options) {
/*
mapml:
1. for query: an array of map-feature elements that it fetches
2. for static templated feature: null
3. for non-templated feature: layer- (with no src) or mapml file (with src)
*/
L.setOptions(this, options);
if (this.options.static) {
this._container = L.DomUtil.create(
'div',
'leaflet-layer',
this.options.pane
);
// must have leaflet-pane class because of new/changed rule in leaflet.css
// info: https://github.com/Leaflet/Leaflet/pull/4597
L.DomUtil.addClass(
this._container,
'leaflet-pane mapml-vector-container'
);
L.setOptions(this.options.renderer, { pane: this._container });
}
this._layers = {};
if (this.options.query) {
this._mapmlFeatures = mapml.features ? mapml.features : mapml;
this.isVisible = true;
let native = this._getNativeVariables(mapml);
this.options.nativeZoom = native.zoom;
this.options.nativeCS = native.cs;
}
if (mapml && !this.options.query) {
let native = this._getNativeVariables(mapml);
//needed to check if the feature is static or not, since this method is used by templated also
if (
!mapml.querySelector('map-extent') &&
mapml.querySelector('map-feature') &&
this.options.static
) {
this._features = {};
this._staticFeature = true;
this.isVisible = true; //placeholder for when this actually gets updated in the future
this.zoomBounds = this._getZoomBounds(mapml, native.zoom);
this.layerBounds = this._getLayerBounds(mapml);
L.extend(this.options, this.zoomBounds);
}
this.addData(mapml, native.cs, native.zoom);
if (this._staticFeature) {
this._resetFeatures();
this.options._leafletLayer._map._addZoomLimit(this);
}
}
},
onAdd: function (map) {
L.FeatureGroup.prototype.onAdd.call(this, map);
if (this._mapmlFeatures)
map.on('featurepagination', this.showPaginationFeature, this);
},
onRemove: function (map) {
if (this._mapmlFeatures) {
map.off('featurepagination', this.showPaginationFeature, this);
delete this._mapmlFeatures;
L.DomUtil.remove(this._container);
}
L.FeatureGroup.prototype.onRemove.call(this, map);
this._map.featureIndex.cleanIndex();
},
getEvents: function () {
if (this._staticFeature) {
return {
moveend: this._handleMoveEnd,
zoomend: this._handleZoomEnd
};
}
return {};
},
// for query
showPaginationFeature: function (e) {
if (this.options.query && this._mapmlFeatures[e.i]) {
let feature = this._mapmlFeatures[e.i];
if (e.type === 'featurepagination') {
// remove map-feature only (keep meta's) when paginating
feature._extentEl.shadowRoot.querySelector('map-feature')?.remove();
} else {
// empty the map-extent shadowRoot
// remove the prev / next one <map-feature> and <map-meta>'s from shadow if there is any
feature._extentEl.shadowRoot.replaceChildren();
}
this.clearLayers();
feature._featureGroup = this.addData(
feature,
this.options.nativeCS,
this.options.nativeZoom
);
// append all map-meta from mapml document
if (e.meta) {
for (let i = 0; i < e.meta.length; i++) {
feature._extentEl.shadowRoot.appendChild(e.meta[i]);
}
}
feature._extentEl.shadowRoot.appendChild(feature);
e.popup._navigationBar.querySelector('p').innerText =
e.i + 1 + '/' + this.options._leafletLayer._totalFeatureCount;
e.popup._content
.querySelector('iframe')
.setAttribute('sandbox', 'allow-same-origin allow-forms');
e.popup._content.querySelector('iframe').srcdoc =
feature.querySelector('map-properties').innerHTML;
// "zoom to here" link need to be re-set for every pagination
this._map.fire('attachZoomLink', { i: e.i, currFeature: feature });
this._map.once(
'popupclose',
function (e) {
this.shadowRoot.innerHTML = '';
},
feature._extentEl
);
}
},
// _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-||layer-||null||[map-feature,...] -> {zoom: _, val: _}
// mapml can be a mapml- element, 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]') &&
+M._metaContentToObject(
mapmlEl.querySelector('map-meta[name=zoom]').getAttribute('content')
).value) ||
0;
nativeCS =
(mapmlEl.querySelector &&
mapmlEl.querySelector('map-meta[name=cs]') &&
M._metaContentToObject(
mapmlEl.querySelector('map-meta[name=cs]').getAttribute('content')
).content) ||
'GCRS';
} else {
// when mapml is null or a layer-/mapml- element
nativeZoom =
(mapml.querySelector &&
mapml.querySelector('map-meta[name=zoom]') &&
+M._metaContentToObject(
mapml.querySelector('map-meta[name=zoom]').getAttribute('content')
).value) ||
0;
nativeCS =
(mapml.querySelector &&
mapml.querySelector('map-meta[name=cs]') &&
M._metaContentToObject(
mapml.querySelector('map-meta[name=cs]').getAttribute('content')
).content) ||
'GCRS';
}
return { zoom: nativeZoom, cs: nativeCS };
},
_handleMoveEnd: function () {
let mapZoom = this._map.getZoom(),
withinZoom =
mapZoom <= this.zoomBounds.maxZoom &&
mapZoom >= this.zoomBounds.minZoom;
this.isVisible =
withinZoom &&
this._layers &&
this.layerBounds &&
this.layerBounds.overlaps(
M.pixelToPCRSBounds(
this._map.getPixelBounds(),
mapZoom,
this._map.options.projection
)
);
this._removeCSS();
},
_handleZoomEnd: function (e) {
let mapZoom = this._map.getZoom();
if (
mapZoom > this.zoomBounds.maxZoom ||
mapZoom < this.zoomBounds.minZoom
) {
this.clearLayers();
return;
}
this._resetFeatures();
},
//sets default if any are missing, better to only replace ones that are missing
_getLayerBounds: function (container) {
if (!container) return null;
let cs = FALLBACK_CS,
projection =
(container.querySelector('map-meta[name=projection]') &&
M._metaContentToObject(
container
.querySelector('map-meta[name=projection]')
.getAttribute('content')
).content.toUpperCase()) ||
FALLBACK_PROJECTION;
try {
let meta =
container.querySelector('map-meta[name=extent]') &&
M._metaContentToObject(
container
.querySelector('map-meta[name=extent]')
.getAttribute('content')
);
let zoom = meta.zoom || 0;
let metaKeys = Object.keys(meta);
for (let i = 0; i < metaKeys.length; i++) {
if (!metaKeys[i].includes('zoom')) {
cs = M.axisToCS(metaKeys[i].split('-')[2]);
break;
}
}
let axes = M.csToAxes(cs);
return M.boundsToPCRSBounds(
L.bounds(
L.point(+meta[`top-left-${axes[0]}`], +meta[`top-left-${axes[1]}`]),
L.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 M.boundsToPCRSBounds(
M[projection].options.crs.tilematrix.bounds(0),
0,
projection,
cs
);
}
},
_resetFeatures: function () {
this.clearLayers();
// since features are removed and re-added by zoom level, need to clean the feature index before re-adding
if (this._map) this._map.featureIndex.cleanIndex();
let map = this._map || this.options._leafletLayer._map;
if (this._features) {
for (let zoom in this._features) {
for (let k = 0; k < this._features[zoom].length; k++) {
let feature = this._features[zoom][k],
checkRender = feature._checkRender(
map.getZoom(),
this.zoomBounds.minZoom,
this.zoomBounds.maxZoom
);
if (checkRender) {
this.addLayer(feature);
}
}
}
}
},
_setZoomTransform: function (center, clampZoom) {
var scale = this._map.getZoomScale(this._map.getZoom(), clampZoom),
translate = center
.multiplyBy(scale)
.subtract(this._map._getNewPixelOrigin(center, this._map.getZoom()))
.round();
if (any3d) {
L.setTransform(this._layers[clampZoom], translate, scale);
} else {
L.setPosition(this._layers[clampZoom], translate);
}
},
_getZoomBounds: function (container, nativeZoom) {
if (!container) return null;
let nMin = 100,
nMax = 0,
features = container.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 = M._metaContentToObject(
container
.querySelector('map-meta[name=projection]')
.getAttribute('content')
).content;
meta = M._metaContentToObject(
container.querySelector('map-meta[name=zoom]').getAttribute('content')
);
} catch (error) {
return {
minZoom: 0,
maxZoom:
M[projection || FALLBACK_PROJECTION].options.resolutions.length - 1,
minNativeZoom: nMin,
maxNativeZoom: nMax
};
}
return {
minZoom: +meta.min,
maxZoom: +meta.max,
minNativeZoom: nMin,
maxNativeZoom: nMax
};
},
addData: function (mapml, nativeCS, nativeZoom) {
var features =
mapml.nodeType === Node.DOCUMENT_NODE || mapml.nodeName === 'LAYER-'
? mapml.getElementsByTagName('map-feature')
: null,
i,
len,
feature;
var linkedStylesheets =
mapml.nodeType === Node.DOCUMENT_NODE
? mapml.querySelector('map-link[rel=stylesheet],map-style')
: null;
if (linkedStylesheets) {
var base =
mapml.querySelector('map-base') &&
mapml.querySelector('map-base').hasAttribute('href')
? new URL(mapml.querySelector('map-base').getAttribute('href')).href
: mapml.URL;
M._parseStylesheetAsHTML(mapml, base, this._container);
}
if (features) {
for (i = 0, len = features.length; i < len; i++) {
// Only add this if geometry is set and not null
feature = features[i];
var geometriesExist =
feature.getElementsByTagName('map-geometry').length &&
feature.getElementsByTagName('map-coordinates').length;
if (geometriesExist) {
if (mapml.nodeType === Node.DOCUMENT_NODE) {
// if the <map-feature> element has migrated from mapml file,
// the featureGroup object should bind with the **CLONED** map-feature element in DOM instead of the feature in mapml
if (!feature._DOMnode) feature._DOMnode = feature.cloneNode(true);
feature._DOMnode._featureGroup = this.addData(
feature._DOMnode,
nativeCS,
nativeZoom
);
} else {
feature._featureGroup = this.addData(feature, nativeCS, nativeZoom);
}
}
}
return this; //if templated this runs
}
//if its a mapml with no more links this runs
var options = this.options;
if (options.filter && !options.filter(mapml)) {
return;
}
if (mapml.classList.length) {
options.className = mapml.classList.value;
}
let zoom = mapml.getAttribute('zoom') || nativeZoom,
title = mapml.querySelector('map-featurecaption');
title = title ? title.innerHTML : 'Feature';
if (mapml.querySelector('map-properties')) {
options.properties = document.createElement('div');
options.properties.classList.add('mapml-popup-content');
options.properties.insertAdjacentHTML(
'afterbegin',
mapml.querySelector('map-properties').innerHTML
);
}
let layer = this.geometryToLayer(mapml, options, nativeCS, +zoom, title);
if (layer) {
// if the layer is being used as a query handler output, it will have
// a color option set. Otherwise, copy classes from the feature
if (!layer.options.color && mapml.hasAttribute('class')) {
layer.options.className = mapml.getAttribute('class');
}
layer.defaultOptions = layer.options;
this.resetStyle(layer);
if (options.onEachFeature) {
layer.bindTooltip(title, { interactive: true, sticky: true });
}
if (this._staticFeature) {
let featureZoom = mapml.getAttribute('zoom') || nativeZoom;
if (featureZoom in this._features) {
this._features[featureZoom].push(layer);
} else {
this._features[featureZoom] = [layer];
}
} else {
this.addLayer(layer);
}
if (mapml.tagName.toUpperCase() === 'MAP-FEATURE') {
mapml._groupEl = layer.options.group;
}
return layer;
}
},
resetStyle: function (layer) {
var style = this.options.style;
if (style) {
// reset any custom styles
L.Util.extend(layer.options, layer.defaultOptions);
this._setLayerStyle(layer, style);
}
},
setStyle: function (style) {
this.eachLayer(function (layer) {
this._setLayerStyle(layer, style);
}, this);
},
_setLayerStyle: function (layer, style) {
if (typeof style === 'function') {
style = style(layer.feature);
}
if (layer.setStyle) {
layer.setStyle(style);
}
},
_removeCSS: function () {
let toDelete = this._container.querySelectorAll(
'link[rel=stylesheet],style'
);
for (let i = 0; i < toDelete.length; i++) {
this._container.removeChild(toDelete[i]);
}
},
geometryToLayer: function (mapml, vectorOptions, nativeCS, zoom, title) {
let geometry =
mapml.tagName.toUpperCase() === 'MAP-FEATURE'
? mapml.getElementsByTagName('map-geometry')[0]
: mapml,
cs = geometry?.getAttribute('cs') || nativeCS,
group = [],
groupOptions = {},
svgGroup = L.SVG.create('g'),
copyOptions = Object.assign({}, vectorOptions);
if (geometry) {
for (let geo of geometry.querySelectorAll(
'map-polygon, map-linestring, map-multilinestring, map-point, map-multipoint'
)) {
group.push(
M.feature(
geo,
Object.assign(copyOptions, {
nativeCS: cs,
nativeZoom: zoom,
projection: this.options.projection,
featureID: mapml.id,
group: svgGroup,
wrappers: this._getGeometryParents(geo.parentElement),
featureLayer: this,
_leafletLayer: this.options._leafletLayer
})
)
);
}
let groupOptions = {
group: svgGroup,
mapmlFeature: mapml,
featureID: mapml.id,
accessibleTitle: title,
onEachFeature: vectorOptions.onEachFeature,
properties: vectorOptions.properties,
_leafletLayer: this.options._leafletLayer
},
collections =
geometry.querySelector('map-multipolygon') ||
geometry.querySelector('map-geometrycollection');
if (collections)
groupOptions.wrappers = this._getGeometryParents(
collections.parentElement
);
return M.featureGroup(group, groupOptions);
}
},
_getGeometryParents: function (subType, elems = []) {
if (subType && subType.tagName.toUpperCase() !== 'MAP-GEOMETRY') {
if (
subType.tagName.toUpperCase() === 'MAP-MULTIPOLYGON' ||
subType.tagName.toUpperCase() === 'MAP-GEOMETRYCOLLECTION'
)
return this._getGeometryParents(subType.parentElement, elems);
return this._getGeometryParents(
subType.parentElement,
elems.concat([subType])
);
} else {
return elems;
}
}
});
export var featureLayer = function (mapml, options) {
return new FeatureLayer(mapml, options);
};