forked from Maps4HTML/MapML.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryHandler.js
More file actions
458 lines (440 loc) · 17 KB
/
QueryHandler.js
File metadata and controls
458 lines (440 loc) · 17 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
import {
Handler,
DomEvent,
DomUtil,
setOptions,
Bounds,
Util as LeafletUtil
} from 'leaflet';
import { MapFeatureLayer } from '../layers/MapFeatureLayer.js';
import { featureRenderer } from '../features/featureRenderer.js';
// Determine if a GeoJSON object has projected (non-CRS:84) coordinates.
// Returns true if a "crs" member is present and non-null, or if coordinate
// values exceed CRS:84 bounds (lon [-180,180], lat [-90,90]), indicating
// meter-based projected units (e.g. from WMS GetFeatureInfo responses).
function _hasProjectedCoordinates(json) {
if (json.crs != null) return true;
let c = _firstCoordinate(json);
return c !== null && (Math.abs(c[0]) > 180 || Math.abs(c[1]) > 90);
}
// Extract the first [x, y] coordinate pair from a GeoJSON object,
// drilling into FeatureCollection → Feature → Geometry → coordinates.
function _firstCoordinate(json) {
if (!json) return null;
let type = json.type && json.type.toUpperCase();
if (type === 'FEATURECOLLECTION') {
if (json.features && json.features.length > 0)
return _firstCoordinate(json.features[0]);
} else if (type === 'FEATURE') {
return _firstCoordinate(json.geometry);
} else if (json.coordinates) {
// Unwrap nested arrays until we reach a [number, number] pair
let coords = json.coordinates;
while (Array.isArray(coords) && Array.isArray(coords[0])) {
coords = coords[0];
}
if (coords.length >= 2 && typeof coords[0] === 'number') return coords;
} else if (type === 'GEOMETRYCOLLECTION' && json.geometries) {
if (json.geometries.length > 0) return _firstCoordinate(json.geometries[0]);
}
return null;
}
export var QueryHandler = Handler.extend({
addHooks: function () {
// get a reference to the actual <map>/<mapml-viewer> element, so we can
// use its layers property to iterate the layers from top down
// evaluating if they are 'on the map' (enabled)
setOptions(this, { mapEl: this._map.options.mapEl });
DomEvent.on(this._map, 'click', this._queryTopLayer, this);
DomEvent.on(this._map, 'keypress', this._queryTopLayerAtMapCenter, this);
},
removeHooks: function () {
DomEvent.off(this._map, 'click', this._queryTopLayer, this);
DomEvent.on(this._map, 'keypress', this._queryTopLayerAtMapCenter, this);
},
_getTopQueryableLayer: function () {
var layers = this.options.mapEl.layers;
// work backwards in document order (top down)
for (var l = layers.length - 1; l >= 0; l--) {
if (layers[l].queryable()) {
return layers[l]._layer;
}
}
},
_queryTopLayerAtMapCenter: function (event) {
setTimeout(() => {
if (
this._map.isFocused &&
!this._map._popupClosed &&
(event.originalEvent.key === ' ' || +event.originalEvent.keyCode === 13)
) {
this._map.fire('click', {
latlng: this._map.getCenter(),
layerPoint: this._map.latLngToLayerPoint(this._map.getCenter()),
containerPoint: this._map.latLngToContainerPoint(
this._map.getCenter()
)
});
} else {
delete this._map._popupClosed;
}
}, 0);
},
_queryTopLayer: function (event) {
var layer = this._getTopQueryableLayer();
if (layer) {
if (layer._mapmlFeatures) delete layer._mapmlFeatures;
this._query(event, layer);
}
},
_query(e, layer) {
var zoom = e.target.getZoom(),
map = this._map,
crs = M[layer.options.projection], // the crs for each extent would be the same
tileSize = map.options.crs.options.crs.tile.bounds.max.x,
container = layer._container,
popupOptions = {
autoClose: false,
autoPan: true,
maxHeight: map.getSize().y * 0.5 - 50,
maxWidth: map.getSize().x * 0.7
},
tcrs2pcrs = function (c) {
return crs.transformation.untransform(c, crs.scale(zoom));
},
tcrs2gcrs = function (c) {
return crs.unproject(
crs.transformation.untransform(c, crs.scale(zoom)),
zoom
);
};
var tcrsClickLoc = crs.latLngToPoint(e.latlng, zoom),
tileMatrixClickLoc = tcrsClickLoc.divideBy(tileSize).floor(),
tileBounds = new Bounds(
tcrsClickLoc.divideBy(tileSize).floor().multiplyBy(tileSize),
tcrsClickLoc.divideBy(tileSize).ceil().multiplyBy(tileSize)
);
let point = this._map.project(e.latlng),
scale = this._map.options.crs.scale(this._map.getZoom()),
pcrsClick = this._map.options.crs.transformation.untransform(
point,
scale
);
let templates = layer.getQueryTemplates(pcrsClick, zoom);
let fetches = [];
var fetchFeatures = function (template, obj) {
const parser = new DOMParser();
return fetch(LeafletUtil.template(template.template, obj), {
redirect: 'follow'
})
.then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.text().then((text) => {
return {
contenttype: response.headers.get('Content-Type'),
text: text
};
});
} else {
throw new Error(response.status);
}
})
.then((response) => {
let features = [];
let queryMetas = [];
let geom =
"<map-geometry cs='gcrs'><map-point><map-coordinates>" +
e.latlng.lng +
' ' +
e.latlng.lat +
'</map-coordinates></map-point></map-geometry>';
if (response.contenttype.startsWith('text/mapml')) {
// the mapmldoc could have <map-meta> elements that are important, perhaps
// also, the mapmldoc can have many features
let mapmldoc = parser.parseFromString(
response.text,
'application/xml'
);
let geometrylessFeatures = mapmldoc.querySelectorAll(
'map-feature:not(:has(map-geometry))'
);
if (geometrylessFeatures.length) {
let g = parser.parseFromString(geom, 'application/xml');
for (let i = 0; i < geometrylessFeatures.length; i++) {
let f = geometrylessFeatures[i];
f.appendChild(g.firstElementChild.cloneNode(true));
}
}
features = Array.prototype.slice.call(
mapmldoc.querySelectorAll('map-feature')
);
// <map-meta> elements for this query
queryMetas = Array.prototype.slice.call(
mapmldoc.querySelectorAll(
'map-meta[name=cs], map-meta[name=zoom], map-meta[name=projection]'
)
);
if (queryMetas.length)
features.forEach((f) => (f.meta = queryMetas));
} else if (
response.contenttype.startsWith('application/json') ||
response.contenttype.startsWith('application/geo+json')
) {
try {
let json = JSON.parse(response.text);
let mapmlLayer = M.geojson2mapml(json, {
projection: layer.options.projection
});
// if crs member is present and non-null, or coordinate
// values exceed CRS:84 range, the response coordinates
// are in the layer's projected CRS, not CRS:84
if (_hasProjectedCoordinates(json)) {
let csMeta = mapmlLayer.querySelector('map-meta[name=cs]');
if (csMeta) csMeta.setAttribute('content', 'pcrs');
}
features = Array.prototype.slice.call(
mapmlLayer.querySelectorAll('map-feature')
);
queryMetas = Array.prototype.slice.call(
mapmlLayer.querySelectorAll(
'map-meta[name=cs], map-meta[name=zoom], map-meta[name=projection]'
)
);
let geometrylessFeatures = features.filter(
(f) => !f.querySelector('map-geometry')
);
if (geometrylessFeatures.length) {
let g = parser.parseFromString(geom, 'text/html');
for (let f of geometrylessFeatures) {
f.appendChild(
g.querySelector('map-geometry').cloneNode(true)
);
}
}
if (queryMetas.length)
features.forEach((f) => (f.meta = queryMetas));
} catch (err) {
// not valid GeoJSON, fall through to HTML rendering
let html = parser.parseFromString(response.text, 'text/html');
let featureDoc = parser.parseFromString(
'<map-feature><map-properties>' +
'</map-properties>' +
geom +
'</map-feature>',
'text/html'
);
if (html.body) {
featureDoc
.querySelector('map-properties')
.appendChild(html.querySelector('html'));
} else {
featureDoc
.querySelector('map-properties')
.append(response.text);
}
features.push(featureDoc.querySelector('map-feature'));
}
} else {
try {
let featureDocument = parser.parseFromString(
response.text,
'application/xml'
);
let featureCollection =
featureDocument.querySelectorAll('map-feature');
if (
featureDocument.querySelector('parsererror') ||
featureCollection.length === 0
) {
throw new Error('parsererror');
}
let g = parser.parseFromString(geom, 'application/xml');
queryMetas = Array.prototype.slice.call(
featureDocument.querySelectorAll(
'map-meta[name=cs], map-meta[name=zoom], map-meta[name=projection]'
)
);
for (let feature of featureCollection) {
if (!feature.querySelector('map-geometry')) {
feature.appendChild(g.firstElementChild.cloneNode(true));
}
feature.meta = queryMetas;
features.push(feature);
}
} catch (err) {
// try the html parser; script elements are marked as non-functional
// by that api, which hopefully works!
let html = parser.parseFromString(response.text, 'text/html');
// synthesize a single feature from text or html content
let featureDoc = parser.parseFromString(
'<map-feature><map-properties>' +
'</map-properties>' +
geom +
'</map-feature>',
'text/html'
);
if (html.body) {
featureDoc
.querySelector('map-properties')
.appendChild(html.querySelector('html'));
} else {
featureDoc
.querySelector('map-properties')
.append(response.text);
}
features.push(featureDoc.querySelector('map-feature'));
}
}
return { features: features, template: template };
})
.catch((err) => {
console.log('Looks like there was a problem. Status: ' + err.message);
});
};
for (let i = 0; i < templates.length; i++) {
var obj = {},
template = templates[i];
// all of the following are locations that might be used in a query, I think.
obj[template.query.tilei] =
tcrsClickLoc.x.toFixed() - tileMatrixClickLoc.x * tileSize;
obj[template.query.tilej] =
tcrsClickLoc.y.toFixed() - tileMatrixClickLoc.y * tileSize;
// this forces the click to the centre of the map extent in the layer crs
obj[template.query.mapi] = map.getSize().divideBy(2).x.toFixed();
obj[template.query.mapj] = map.getSize().divideBy(2).y.toFixed();
obj[template.query.pixelleft] = crs.pointToLatLng(tcrsClickLoc, zoom).lng;
obj[template.query.pixeltop] = crs.pointToLatLng(tcrsClickLoc, zoom).lat;
obj[template.query.pixelright] = crs.pointToLatLng(
tcrsClickLoc.add([1, 1]),
zoom
).lng;
obj[template.query.pixelbottom] = crs.pointToLatLng(
tcrsClickLoc.add([1, 1]),
zoom
).lat;
obj[template.query.column] = tileMatrixClickLoc.x;
obj[template.query.row] = tileMatrixClickLoc.y;
obj[template.query.x] = tcrsClickLoc.x.toFixed();
obj[template.query.y] = tcrsClickLoc.y.toFixed();
// whereas the layerPoint is calculated relative to the origin plus / minus any
// pan movements so is equal to containerPoint at first before any pans, but
// changes as the map pans.
obj[template.query.easting] = tcrs2pcrs(tcrsClickLoc).x;
obj[template.query.northing] = tcrs2pcrs(tcrsClickLoc).y;
obj[template.query.longitude] = tcrs2gcrs(tcrsClickLoc).lng;
obj[template.query.latitude] = tcrs2gcrs(tcrsClickLoc).lat;
obj[template.query.zoom] = zoom;
obj[template.query.width] = map.getSize().x;
obj[template.query.height] = map.getSize().y;
// assumes the click is at the centre of the map, per template.query.mapi, mapj above
obj[template.query.mapbottom] = tcrs2pcrs(
tcrsClickLoc.add(map.getSize().divideBy(2))
).y;
obj[template.query.mapleft] = tcrs2pcrs(
tcrsClickLoc.subtract(map.getSize().divideBy(2))
).x;
obj[template.query.maptop] = tcrs2pcrs(
tcrsClickLoc.subtract(map.getSize().divideBy(2))
).y;
obj[template.query.mapright] = tcrs2pcrs(
tcrsClickLoc.add(map.getSize().divideBy(2))
).x;
obj[template.query.tilebottom] = tcrs2pcrs(tileBounds.max).y;
obj[template.query.tileleft] = tcrs2pcrs(tileBounds.min).x;
obj[template.query.tiletop] = tcrs2pcrs(tileBounds.min).y;
obj[template.query.tileright] = tcrs2pcrs(tileBounds.max).x;
// add hidden or other variables that may be present into the values to
// be processed by Util.template below.
for (var v in template.query) {
if (
[
'mapi',
'mapj',
'tilei',
'tilej',
'row',
'col',
'x',
'y',
'easting',
'northing',
'longitude',
'latitude',
'width',
'height',
'zoom',
'mapleft',
'mapright',
',maptop',
'mapbottom',
'tileleft',
'tileright',
'tiletop',
'tilebottom',
'pixeltop',
'pixelbottom',
'pixelleft',
'pixelright'
].indexOf(v) < 0
) {
obj[v] = template.query[v];
}
}
fetches.push(fetchFeatures(template, obj));
}
Promise.allSettled(fetches).then((results) => {
layer._mapmlFeatures = [];
// f is an array of {features[], template}
for (let f of results) {
if (f.status === 'fulfilled') {
// create connection between queried <map-feature> and its parent <map-link>
for (let feature of f.value.features) {
feature._linkEl = f.value.template.linkEl;
}
layer._mapmlFeatures = layer._mapmlFeatures.concat(f.value.features);
}
}
if (layer._mapmlFeatures.length > 0)
displayFeaturesPopup(layer._mapmlFeatures, e.latlng);
});
function displayFeaturesPopup(features, loc) {
if (features.length === 0) return;
let f = new MapFeatureLayer(features, {
// pass the vector layer a renderer of its own, otherwise leaflet
// puts everything into the overlayPane
renderer: featureRenderer(),
// pass the vector layer the container for the parent into which
// it will append its own container for rendering into
pane: container,
//color: 'yellow',
// instead of unprojecting and then projecting and scaling,
// a much smarter approach would be to scale at the current
// zoom
projection: map.options.projection,
_leafletLayer: layer,
query: true,
mapEl: map.options.mapEl
});
f.addTo(layer);
let div = DomUtil.create('div', 'mapml-popup-content'),
c = DomUtil.create('iframe');
c.style = 'border: none';
c.srcdoc = features[0].querySelector(
'map-feature map-properties'
).innerHTML;
c.setAttribute('sandbox', 'allow-same-origin allow-forms');
div.appendChild(c);
// passing a latlng to the popup is necessary for when there is no
// geometry / null geometry
layer._totalFeatureCount = features.length;
layer.bindPopup(div, popupOptions).openPopup(loc);
layer.on('popupclose', function () {
layer.removeLayer(f);
});
f.showPaginationFeature({
i: 0,
popup: layer._popup
});
}
}
});