ol-elevation-profile 0.6.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -1
- package/dist/ol-elevation-profile.css +22 -6
- package/dist/ol-elevation-profile.esm.js +960 -63
- package/dist/ol-elevation-profile.esm.min.js +7 -5
- package/dist/ol-elevation-profile.js +962 -66
- package/dist/ol-elevation-profile.min.js +7 -5
- package/package.json +4 -3
- package/src/ol-elevation-profile.css +22 -6
- package/src/ol-elevation-profile.js +960 -63
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Synchronized elevation profile control for OpenLayers, rendered with d3.
|
|
3
3
|
*
|
|
4
|
-
* Reads elevation (Z) directly from 3D line geometries (`[lon, lat, z]`)
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Reads elevation (Z) directly from 3D line geometries (`[lon, lat, z]`). A track without
|
|
5
|
+
* Z is completed from a terrain model - keyless AWS Terrain Tiles by default, which means
|
|
6
|
+
* the control fetches tiles on its own; set `dem: null` to keep it entirely offline.
|
|
7
|
+
* Clicking (or hovering) a track shows its profile; a marker stays synchronized on both
|
|
8
|
+
* the map and the chart.
|
|
7
9
|
*
|
|
8
10
|
* Peer dependencies (provided by the host application, not bundled):
|
|
9
11
|
* - OpenLayers >= 6 (https://openlayers.org/)
|
|
@@ -15,7 +17,8 @@
|
|
|
15
17
|
import Control from 'ol/control/Control.js';
|
|
16
18
|
import Overlay from 'ol/Overlay.js';
|
|
17
19
|
import { unByKey } from 'ol/Observable.js';
|
|
18
|
-
import { toLonLat } from 'ol/proj.js';
|
|
20
|
+
import { toLonLat, fromLonLat, transform, get as getProj } from 'ol/proj.js';
|
|
21
|
+
import TileState from 'ol/TileState.js';
|
|
19
22
|
import { getDistance } from 'ol/sphere.js';
|
|
20
23
|
import { boundingExtent } from 'ol/extent.js';
|
|
21
24
|
import * as d3 from 'd3';
|
|
@@ -34,25 +37,26 @@ import * as d3 from 'd3';
|
|
|
34
37
|
const DEFAULTS = {
|
|
35
38
|
immersion: 'docked',
|
|
36
39
|
position: 'bottom',
|
|
37
|
-
width: 520, //
|
|
40
|
+
width: 520, // number (px, capped to the map width) or 'auto'/'100%'/'full' = map width
|
|
38
41
|
height: 180,
|
|
39
42
|
margins: { unit: 'px', top: 20, right: 24, bottom: 30, left: 48 },
|
|
40
43
|
units: 'meters',
|
|
41
44
|
dataProjection: null,
|
|
45
|
+
dem: 'terrarium', // AWS tiles by default; null = off; or { url, encoding, zoom, maxTiles }
|
|
42
46
|
maxPoints: 2000,
|
|
43
|
-
smoothing: 0, //
|
|
47
|
+
smoothing: 0, // elevation smoothing: window in METRES (0 = none)
|
|
44
48
|
theme: 'steelblue',
|
|
45
|
-
color: null, // null=
|
|
49
|
+
color: null, // null = theme, 'auto' = track colour, or a CSS colour
|
|
46
50
|
trackLayer: null,
|
|
47
51
|
transparency: false, // false | true | nombre 0..1
|
|
48
52
|
transparencyLevel: 0.45,
|
|
49
53
|
grid: true,
|
|
50
54
|
slope: false,
|
|
51
55
|
slopeClassSize: 2.5,
|
|
52
|
-
slopeColors: null, // null =
|
|
53
|
-
slopeSeparators: true, //
|
|
56
|
+
slopeColors: null, // null = blue->red ramp (HSL); otherwise an interpolated array
|
|
57
|
+
slopeSeparators: true, // vertical line at each class change
|
|
54
58
|
slopeLegend: true,
|
|
55
|
-
maxClasses: 8, //
|
|
59
|
+
maxClasses: 8, // maximum number of slope classes (colours + legend)
|
|
56
60
|
xTicks: null,
|
|
57
61
|
yTicks: null,
|
|
58
62
|
show: 'click',
|
|
@@ -61,11 +65,12 @@ import * as d3 from 'd3';
|
|
|
61
65
|
followMap: true,
|
|
62
66
|
marker: true,
|
|
63
67
|
hideOnMapClick: true,
|
|
64
|
-
responsive: true, //
|
|
65
|
-
mobileBreakpoint: 640, // <=
|
|
66
|
-
zoom: false, //
|
|
67
|
-
|
|
68
|
-
|
|
68
|
+
responsive: true, // adapts width/placement, mobile included
|
|
69
|
+
mobileBreakpoint: 640, // <= screen width -> mobile mode (100% width, top/bottom)
|
|
70
|
+
zoom: false, // start/end buttons cropping map + profile to A..B
|
|
71
|
+
exportPng: false, // toolbar button exporting the panel as a PNG
|
|
72
|
+
ignoreStops: true, // duration = moving time (stops excluded)
|
|
73
|
+
stopSpeed: 0.5, // stop threshold in m/s (~1.8 km/h)
|
|
69
74
|
tooltipItems: ['distance', 'elevation'],
|
|
70
75
|
headerItems: ['distance', 'ascent', 'descent', 'minmax'],
|
|
71
76
|
titleProperty: 'name',
|
|
@@ -75,7 +80,9 @@ import * as d3 from 'd3';
|
|
|
75
80
|
ascent: 'D+', descent: 'D-', empty: 'Cliquez un tracé',
|
|
76
81
|
time: 'Temps', duration: 'Durée',
|
|
77
82
|
durationUnits: { s: 'sec', m: 'min', h: 'h', d: 'j' },
|
|
78
|
-
zoomStart: 'Définir le début (A)', zoomEnd: 'Définir la fin (B)', zoomAll: 'Tout voir'
|
|
83
|
+
zoomStart: 'Définir le début (A)', zoomEnd: 'Définir la fin (B)', zoomAll: 'Tout voir',
|
|
84
|
+
exportPng: 'Exporter en PNG',
|
|
85
|
+
loading: 'Chargement du profil altimétrique'
|
|
79
86
|
}
|
|
80
87
|
};
|
|
81
88
|
|
|
@@ -92,15 +99,44 @@ import * as d3 from 'd3';
|
|
|
92
99
|
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
93
100
|
const isUrl = (v) => typeof v === 'string' && /^(https?:)?\/\/|^mailto:/i.test(v);
|
|
94
101
|
|
|
95
|
-
|
|
96
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Coordinate segments to profile, whatever the geometry type: an array of point arrays.
|
|
104
|
+
*
|
|
105
|
+
* A polygon is profiled along its **outer ring only**; the holes are not part of the
|
|
106
|
+
* outline itself. The ring being closed, the profile returns to its starting point -
|
|
107
|
+
* that is the outline, faithfully, not a defect.
|
|
108
|
+
*
|
|
109
|
+
* One place for the five that used to test `getType()` themselves: they all wrapped
|
|
110
|
+
* `getCoordinates()` in one extra array unless it was a MultiLineString, which silently
|
|
111
|
+
* made a polygon iterate over its rings as if they were points.
|
|
112
|
+
*/
|
|
113
|
+
function geomLines(geom) {
|
|
114
|
+
if (!geom || !geom.getCoordinates) return [];
|
|
115
|
+
const c = geom.getCoordinates();
|
|
116
|
+
switch (geom.getType()) {
|
|
117
|
+
case 'LineString':
|
|
118
|
+
case 'LinearRing': return [c];
|
|
119
|
+
case 'MultiLineString': return c;
|
|
120
|
+
case 'Polygon': return c.length ? [c[0]] : [];
|
|
121
|
+
case 'MultiPolygon': return c.map((poly) => poly[0]).filter(Boolean);
|
|
122
|
+
default: return [];
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Whether a geometry can be profiled at all - the map-selection filter and nothing more. */
|
|
127
|
+
function isProfilable(geom) {
|
|
128
|
+
return !!geom && /^(Multi)?(LineString|Polygon)$|^LinearRing$/.test(geom.getType());
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Flat array of timestamps (epoch ms) aligned on the flat coordinate order, read from
|
|
132
|
+
// properties.coordTimes (ISO or number), coordinateProperties.times, or the 4th (M) dimension.
|
|
97
133
|
function extractTimes(feature, lines) {
|
|
98
134
|
const props = (feature && feature.getProperties) ? feature.getProperties() : {};
|
|
99
135
|
let raw = props.coordTimes;
|
|
100
136
|
if (raw == null && props.coordinateProperties) raw = props.coordinateProperties.times || props.coordinateProperties.coordTimes;
|
|
101
137
|
let flat = null;
|
|
102
138
|
if (Array.isArray(raw)) flat = Array.isArray(raw[0]) ? raw.reduce((a, b) => a.concat(b), []) : raw.slice();
|
|
103
|
-
if (!flat && lines) { //
|
|
139
|
+
if (!flat && lines) { // fallback: 4th M dimension (XYZM layout)
|
|
104
140
|
const tmp = []; let any = false;
|
|
105
141
|
for (const seg of lines) for (const c of seg) { const v = c.length > 3 ? c[3] : null; tmp.push(v); if (v != null && isFinite(v)) any = true; }
|
|
106
142
|
flat = any ? tmp : null;
|
|
@@ -151,8 +187,541 @@ import * as d3 from 'd3';
|
|
|
151
187
|
const ICON_EXPAND = '<svg viewBox="0 0 24 24"><path d="M3 19l5-7 4 4 4-6 5 9z" fill="currentColor" opacity=".85"/></svg>';
|
|
152
188
|
const ICON_A = '<svg viewBox="0 0 24 24"><path d="M7 5v14M11 12h8m0 0-3-3m3 3-3 3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
|
153
189
|
const ICON_B = '<svg viewBox="0 0 24 24"><path d="M17 5v14M13 12H5m0 0 3-3m-3 3 3 3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
|
190
|
+
const ICON_PNG = '<svg viewBox="0 0 24 24"><path d="M12 4v10m0 0 4-4m-4 4-4-4M5 18h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
|
154
191
|
const ICON_ALL = '<svg viewBox="0 0 24 24"><path d="M4 12h16M4 12l4-4M4 12l4 4M20 12l-4-4M20 12l-4 4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
|
155
192
|
|
|
193
|
+
// ----- digital elevation model (DEM) -----------------------------------
|
|
194
|
+
/**
|
|
195
|
+
* Known terrain-tile sources.
|
|
196
|
+
*
|
|
197
|
+
* A PNG tile carries elevation in its R/G/B channels; it is read on a canvas rather
|
|
198
|
+
* than queried point by point from an API. That is what makes a 10 000-point track a
|
|
199
|
+
* handful of requests, with no key, no quota and no rate limit — where the free
|
|
200
|
+
* elevation APIs cap out at 100 or 200 points per call.
|
|
201
|
+
*
|
|
202
|
+
* Attribution is not automatic: the library does not own the map. It is up to the
|
|
203
|
+
* application to carry `attributions` in its own basemap source - and since the DEM is
|
|
204
|
+
* on by default, that obligation arrives without having been asked for. `dem: null`
|
|
205
|
+
* turns the whole thing off.
|
|
206
|
+
*/
|
|
207
|
+
const DEM_PRESETS = {
|
|
208
|
+
terrarium: {
|
|
209
|
+
url: 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png',
|
|
210
|
+
encoding: 'terrarium',
|
|
211
|
+
maxZoom: 14,
|
|
212
|
+
attributions: 'Elevation: <a href="https://registry.opendata.aws/terrain-tiles/">Terrain Tiles</a> (AWS Open Data)'
|
|
213
|
+
},
|
|
214
|
+
/**
|
|
215
|
+
* IGN Géoplateforme, serving the RGE ALTI over France and its overseas territories.
|
|
216
|
+
*
|
|
217
|
+
* A point API rather than tiles, hence its own sampler: it answers 200 points per
|
|
218
|
+
* request and announces one request per second, so a 10 000 point track takes about
|
|
219
|
+
* fifty calls spread over as many seconds. In exchange it is metre-accurate where the
|
|
220
|
+
* world models are at ninety.
|
|
221
|
+
*
|
|
222
|
+
* **No key is required** on the public endpoint - verified against the live service.
|
|
223
|
+
* `apiKey` exists for a deployment that does demand one; it is appended as a query
|
|
224
|
+
* parameter, named by `apiKeyParam`.
|
|
225
|
+
*
|
|
226
|
+
* Outside its coverage the service does not error: it answers OUT_OF_COVERAGE for the
|
|
227
|
+
* point. No border is coded here - one asks, and it says itself where it does not know.
|
|
228
|
+
*/
|
|
229
|
+
ign: {
|
|
230
|
+
api: 'ign',
|
|
231
|
+
url: 'https://data.geopf.fr/altimetrie/1.0/calcul/alti/rest/elevation.json',
|
|
232
|
+
resource: 'ign_rge_alti_wld',
|
|
233
|
+
batch: 200, // more fits, but the URL grows ~20 bytes a point and hits 414
|
|
234
|
+
minInterval: 1100, // ms between calls; the service announces 1 req/s
|
|
235
|
+
attributions: 'Elevation: <a href="https://geoservices.ign.fr/rgealti">RGE ALTI</a> (IGN)'
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/** Value the IGN service returns where it holds no measurement. */
|
|
240
|
+
const IGN_NO_DATA = -99999;
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Request URL for one batch, in the order given: the response returns the elevations in
|
|
244
|
+
* the same one.
|
|
245
|
+
*
|
|
246
|
+
* `zonly=true` cuts the response down to the elevations alone, without echoing the
|
|
247
|
+
* coordinates - a third of the weight for the same information. Coordinates rounded to
|
|
248
|
+
* the millionth of a degree, about ten centimetres: beyond that one only adds digits to
|
|
249
|
+
* the URL.
|
|
250
|
+
*/
|
|
251
|
+
function ignUrl(cfg, pts) {
|
|
252
|
+
const f = (v) => v.toFixed(6);
|
|
253
|
+
const sep = cfg.url.indexOf('?') >= 0 ? '&' : '?';
|
|
254
|
+
let u = cfg.url + sep + 'resource=' + encodeURIComponent(cfg.resource) +
|
|
255
|
+
'&delimiter=|&zonly=true' +
|
|
256
|
+
'&lon=' + pts.map((p) => f(p[0])).join('|') +
|
|
257
|
+
'&lat=' + pts.map((p) => f(p[1])).join('|');
|
|
258
|
+
if (cfg.apiKey) u += '&' + (cfg.apiKeyParam || 'apikey') + '=' + encodeURIComponent(cfg.apiKey);
|
|
259
|
+
return u;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Sampler for the IGN service: batches, paces, and maps out-of-coverage to null.
|
|
264
|
+
*
|
|
265
|
+
* A batch whose response does not carry exactly as many elevations as points were asked
|
|
266
|
+
* for fails the whole fill. Elevations one can no longer map to their points are worse
|
|
267
|
+
* than absent ones: they would land on the wrong places, silently.
|
|
268
|
+
*/
|
|
269
|
+
function ignSampler(cfg) {
|
|
270
|
+
const size = Math.max(1, cfg.batch || 200);
|
|
271
|
+
const gap = cfg.minInterval || 0;
|
|
272
|
+
return (lonlats) => {
|
|
273
|
+
const out = [];
|
|
274
|
+
let last = 0;
|
|
275
|
+
const step = (i) => {
|
|
276
|
+
if (i >= lonlats.length) return Promise.resolve(out);
|
|
277
|
+
const chunk = lonlats.slice(i, i + size);
|
|
278
|
+
const wait = Math.max(0, gap - (Date.now() - last));
|
|
279
|
+
return new Promise((r) => setTimeout(r, wait))
|
|
280
|
+
.then(() => { last = Date.now(); return fetch(ignUrl(cfg, chunk)); })
|
|
281
|
+
.then((r) => (r && r.ok) ? r.json() : null)
|
|
282
|
+
.then((body) => {
|
|
283
|
+
const z = body && body.elevations;
|
|
284
|
+
if (!Array.isArray(z) || z.length !== chunk.length) return null;
|
|
285
|
+
for (const v of z) out.push((v == null || v <= IGN_NO_DATA) ? null : v);
|
|
286
|
+
return step(i + size);
|
|
287
|
+
});
|
|
288
|
+
};
|
|
289
|
+
return step(0);
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const DEM_DEFAULTS = { source: 'terrarium', zoom: 'auto', maxZoom: 14, maxTiles: 32, concurrency: 6, tileSize: 256 };
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* RGB → metres decoders, one per encoding convention.
|
|
297
|
+
*
|
|
298
|
+
* `encoding` also takes a function `(r, g, b, a) => metres`, for a tile set that packs
|
|
299
|
+
* elevation its own way. Return null where the pixel carries no measurement: the fill is
|
|
300
|
+
* abandoned rather than guessed.
|
|
301
|
+
*
|
|
302
|
+
* A GeoServer greyscale DEM is NOT decoded here. What a WMS returns is a rendered image,
|
|
303
|
+
* stretched and quantised by its style, not the coverage values; reading it back would
|
|
304
|
+
* be reading the rendering. Those go through `featureInfo`, which asks the server for the
|
|
305
|
+
* band value itself (see demConfig).
|
|
306
|
+
*/
|
|
307
|
+
const DEM_DECODERS = {
|
|
308
|
+
terrarium: (r, g, b) => (r * 256 + g + b / 256) - 32768,
|
|
309
|
+
mapbox: (r, g, b) => -10000 + (r * 65536 + g * 256 + b) * 0.1
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
/** Half the Web Mercator world, in metres: the bound of EPSG:3857. */
|
|
313
|
+
const MERC_HALF = 20037508.342789244;
|
|
314
|
+
|
|
315
|
+
/** Extent of an XYZ tile in EPSG:3857, for the WMS requests built below. */
|
|
316
|
+
function tileExtent(z, x, y) {
|
|
317
|
+
const span = 2 * MERC_HALF / Math.pow(2, z);
|
|
318
|
+
const minX = -MERC_HALF + x * span, maxY = MERC_HALF - y * span;
|
|
319
|
+
return [minX, maxY - span, minX + span, maxY];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function query(base, params) {
|
|
323
|
+
const sep = base.indexOf('?') >= 0 ? '&' : '?';
|
|
324
|
+
return base.replace(/[?&]$/, '') + sep +
|
|
325
|
+
Object.keys(params).map((k) => k + '=' + encodeURIComponent(params[k])).join('&');
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* WMS GetMap URL covering one XYZ tile, so a WMS behaves like any other tile source.
|
|
330
|
+
*
|
|
331
|
+
* The axis-order trap: WMS 1.3.0 names the reference system `CRS`, 1.1.1 names it `SRS`,
|
|
332
|
+
* and sending the wrong one gets the request rejected or silently mis-georeferenced.
|
|
333
|
+
* The version actually in force decides, after the caller's params are merged in.
|
|
334
|
+
*/
|
|
335
|
+
function wmsTileUrl(w, z, x, y, tileSize) {
|
|
336
|
+
const p = Object.assign({
|
|
337
|
+
SERVICE: 'WMS', REQUEST: 'GetMap', VERSION: '1.3.0', FORMAT: 'image/png',
|
|
338
|
+
TRANSPARENT: 'false', STYLES: ''
|
|
339
|
+
}, w.params || {});
|
|
340
|
+
const key = String(p.VERSION).indexOf('1.1') === 0 ? 'SRS' : 'CRS';
|
|
341
|
+
delete p.SRS; delete p.CRS;
|
|
342
|
+
p[key] = w.projection || 'EPSG:3857';
|
|
343
|
+
p.LAYERS = w.layers;
|
|
344
|
+
p.WIDTH = tileSize; p.HEIGHT = tileSize;
|
|
345
|
+
p.BBOX = tileExtent(z, x, y).join(',');
|
|
346
|
+
return query(w.url, p);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Where a tile comes from: an OpenLayers source, a WMS, or an XYZ template.
|
|
351
|
+
*
|
|
352
|
+
* Handing an `ol/source/TileImage` (XYZ, TileWMS, or any subclass) delegates URL building
|
|
353
|
+
* to OpenLayers itself, which already knows that source's quirks - subdomains, custom
|
|
354
|
+
* params, tile grid. Cheaper and safer than reimplementing each one here.
|
|
355
|
+
*/
|
|
356
|
+
function tileUrlFn(cfg) {
|
|
357
|
+
const src = cfg.olSource;
|
|
358
|
+
if (src && typeof src.getTileUrlFunction === 'function') {
|
|
359
|
+
const fn = src.getTileUrlFunction();
|
|
360
|
+
const proj = getProj('EPSG:3857');
|
|
361
|
+
return (z, x, y) => fn([z, x, y], 1, proj);
|
|
362
|
+
}
|
|
363
|
+
if (cfg.wms) return (z, x, y) => wmsTileUrl(cfg.wms, z, x, y, cfg.tileSize);
|
|
364
|
+
return (z, x, y) => cfg.url.replace('{z}', z).replace('{x}', x).replace('{y}', y);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Values of one DataTile, or null if it never arrived.
|
|
369
|
+
*
|
|
370
|
+
* A DataTile carries no URL: it is loaded by the source itself and its values are read
|
|
371
|
+
* back with getData(). The state has to be watched rather than awaited - OpenLayers
|
|
372
|
+
* announces it through a `change` event, not a promise.
|
|
373
|
+
*/
|
|
374
|
+
function loadDataTile(tile) {
|
|
375
|
+
return new Promise((resolve) => {
|
|
376
|
+
const settle = () => {
|
|
377
|
+
const st = tile.getState();
|
|
378
|
+
if (st === TileState.LOADED) { resolve(tile.getData ? tile.getData() : null); return true; }
|
|
379
|
+
if (st === TileState.ERROR || st === TileState.EMPTY) { resolve(null); return true; }
|
|
380
|
+
return false;
|
|
381
|
+
};
|
|
382
|
+
if (settle()) return;
|
|
383
|
+
const onChange = () => { if (settle()) tile.removeEventListener('change', onChange); };
|
|
384
|
+
tile.addEventListener('change', onChange);
|
|
385
|
+
if (tile.load) tile.load();
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Sampler for an `ol/source/DataTile` - `ol/source/GeoTIFF` above all.
|
|
391
|
+
*
|
|
392
|
+
* Its own path because such a source shares nothing with the XYZ one: no URL, no Web
|
|
393
|
+
* Mercator, no 256 pixel tiles. A GeoTIFF keeps **its own projection and its own tile
|
|
394
|
+
* grid**, both only known once `getView()` has resolved, and its values are real numbers
|
|
395
|
+
* rather than colours - so nothing here goes through a decoder.
|
|
396
|
+
*
|
|
397
|
+
* Positions are held in grid pixels, as with the XYZ tiles and for the same reason: the
|
|
398
|
+
* four neighbours of a point straddle two tiles as soon as it runs along an edge.
|
|
399
|
+
*
|
|
400
|
+
* `normalize: false` matters on the source, otherwise OpenLayers rescales the values to
|
|
401
|
+
* 0..1 and the profile comes out in fractions of nothing.
|
|
402
|
+
*/
|
|
403
|
+
function dataTileSampler(cfg) {
|
|
404
|
+
const src = cfg.olSource;
|
|
405
|
+
const band = cfg.band || 0;
|
|
406
|
+
return (lonlats) => {
|
|
407
|
+
// getView() is only awaited when the grid is not known yet - which is the GeoTIFF
|
|
408
|
+
// case, where it settles once the metadata has been read. On a plain DataTile that
|
|
409
|
+
// promise never settles at all, and awaiting it unconditionally hangs the fill.
|
|
410
|
+
const known = src.getTileGrid && src.getTileGrid();
|
|
411
|
+
const ready = known ? Promise.resolve(null) : Promise.resolve(src.getView ? src.getView() : null);
|
|
412
|
+
return ready.then((view) => {
|
|
413
|
+
const grid = known || (src.getTileGrid && src.getTileGrid()) || (view && view.tileGrid);
|
|
414
|
+
if (!grid) return null;
|
|
415
|
+
const proj = getProj((view && view.projection) || (src.getProjection && src.getProjection()) || 'EPSG:3857');
|
|
416
|
+
const zs = grid.getResolutions ? grid.getResolutions().length - 1 : 0;
|
|
417
|
+
const bands = src.bandCount || 1;
|
|
418
|
+
const coords = lonlats.map((ll) => transform([ll[0], ll[1]], 'EPSG:4326', proj));
|
|
419
|
+
|
|
420
|
+
// Finest level whose tile count stays within maxTiles, as for the XYZ tiles: it is
|
|
421
|
+
// the tiling that widens with the track, not the model that degrades.
|
|
422
|
+
// Pixel bounds of the coverage, when it declares an extent. A point inside the raster
|
|
423
|
+
// but within half a pixel of its edge lands on a neighbour that does not exist: its
|
|
424
|
+
// tile would come back empty and the all-or-nothing rule would drop the whole track.
|
|
425
|
+
// Half a pixel of tolerance at the borders, as on any regular grid.
|
|
426
|
+
const ext = (grid.getExtent && grid.getExtent()) || (view && view.extent) || null;
|
|
427
|
+
const plan = (z) => {
|
|
428
|
+
const res = grid.getResolution(z), origin = grid.getOrigin(z);
|
|
429
|
+
let ts = grid.getTileSize(z); ts = Array.isArray(ts) ? ts : [ts, ts];
|
|
430
|
+
const cols = ext ? Math.round((ext[2] - ext[0]) / res) : Infinity;
|
|
431
|
+
const rows = ext ? Math.round((ext[3] - ext[1]) / res) : Infinity;
|
|
432
|
+
const clampI = (i) => Math.min(cols - 1, Math.max(0, i));
|
|
433
|
+
const clampJ = (j) => Math.min(rows - 1, Math.max(0, j));
|
|
434
|
+
const need = new Map();
|
|
435
|
+
const at = coords.map((c) => {
|
|
436
|
+
const px = (c[0] - origin[0]) / res - 0.5, py = (origin[1] - c[1]) / res - 0.5;
|
|
437
|
+
const i0 = clampI(Math.floor(px)), j0 = clampJ(Math.floor(py));
|
|
438
|
+
for (let di = 0; di < 2; di++) for (let dj = 0; dj < 2; dj++) {
|
|
439
|
+
const tx = Math.floor(clampI(i0 + di) / ts[0]), ty = Math.floor(clampJ(j0 + dj) / ts[1]);
|
|
440
|
+
need.set(tx + '/' + ty, [tx, ty]);
|
|
441
|
+
}
|
|
442
|
+
// Interpolation fractions clamped too: a point beyond the last pixel centre keeps
|
|
443
|
+
// that pixel's value rather than extrapolating past the edge of the data.
|
|
444
|
+
return { i0, j0, tx: Math.min(1, Math.max(0, px - i0)), ty: Math.min(1, Math.max(0, py - j0)), clampI, clampJ };
|
|
445
|
+
});
|
|
446
|
+
return { res, origin, ts, need, at, clampI, clampJ };
|
|
447
|
+
};
|
|
448
|
+
let z = zs, p = plan(z);
|
|
449
|
+
while (z > 0 && p.need.size > cfg.maxTiles) { z--; p = plan(z); }
|
|
450
|
+
if (p.need.size > cfg.maxTiles) return null;
|
|
451
|
+
|
|
452
|
+
const keys = Array.from(p.need.keys());
|
|
453
|
+
return Promise.all(keys.map((k) => {
|
|
454
|
+
const t = p.need.get(k);
|
|
455
|
+
return loadDataTile(src.getTile(z, t[0], t[1], 1, proj)).then((d) => [k, d]);
|
|
456
|
+
})).then((pairs) => {
|
|
457
|
+
const tiles = new Map(pairs);
|
|
458
|
+
const value = (i, j) => {
|
|
459
|
+
const tx = Math.floor(p.clampI(i) / p.ts[0]), ty = Math.floor(p.clampJ(j) / p.ts[1]);
|
|
460
|
+
i = p.clampI(i); j = p.clampJ(j);
|
|
461
|
+
const d = tiles.get(tx + '/' + ty);
|
|
462
|
+
if (!d) return null;
|
|
463
|
+
const col = i - tx * p.ts[0], row = j - ty * p.ts[1];
|
|
464
|
+
const v = d[(row * p.ts[0] + col) * bands + band];
|
|
465
|
+
return (v == null || !isFinite(v)) ? null : v;
|
|
466
|
+
};
|
|
467
|
+
return p.at.map((n) => {
|
|
468
|
+
const a = value(n.i0, n.j0), b = value(n.i0 + 1, n.j0);
|
|
469
|
+
const c = value(n.i0, n.j0 + 1), e = value(n.i0 + 1, n.j0 + 1);
|
|
470
|
+
if (a == null || b == null || c == null || e == null) return null;
|
|
471
|
+
const north = a + (b - a) * n.tx, south = c + (e - c) * n.tx;
|
|
472
|
+
return north + (south - north) * n.ty;
|
|
473
|
+
});
|
|
474
|
+
});
|
|
475
|
+
});
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* WMS GetFeatureInfo sampler: one request per point, for a coverage served as a rendered
|
|
481
|
+
* greyscale that cannot be decoded from its pixels.
|
|
482
|
+
*
|
|
483
|
+
* **It is slow**, unavoidably: a thousand-point track is a thousand round trips, where a
|
|
484
|
+
* tile source needs a handful. Worth it only when nothing else can reach the data - and
|
|
485
|
+
* `concurrency` is what keeps it bearable.
|
|
486
|
+
*/
|
|
487
|
+
function featureInfoSampler(cfg) {
|
|
488
|
+
const fi = cfg.featureInfo;
|
|
489
|
+
const lanes = Math.max(1, cfg.concurrency || 6);
|
|
490
|
+
return (lonlats) => {
|
|
491
|
+
const out = new Array(lonlats.length);
|
|
492
|
+
let next = 0, broken = false;
|
|
493
|
+
const one = () => {
|
|
494
|
+
if (broken || next >= lonlats.length) return Promise.resolve();
|
|
495
|
+
const i = next++;
|
|
496
|
+
return fetch(featureInfoUrl(fi, lonlats[i]))
|
|
497
|
+
.then((r) => (r && r.ok) ? r.json() : null)
|
|
498
|
+
.then((body) => { out[i] = bandValue(body, fi.property); return one(); })
|
|
499
|
+
.catch(() => { broken = true; });
|
|
500
|
+
};
|
|
501
|
+
const running = [];
|
|
502
|
+
for (let i = 0; i < Math.min(lanes, lonlats.length); i++) running.push(one());
|
|
503
|
+
return Promise.all(running).then(() => broken ? null : out);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** GetFeatureInfo URL for one point: a one-pixel image centred on it. */
|
|
508
|
+
function featureInfoUrl(fi, ll) {
|
|
509
|
+
const c = fromLonLat([ll[0], ll[1]]);
|
|
510
|
+
const d = fi.resolution || 1; // half-size of the box, in metres
|
|
511
|
+
const p = Object.assign({
|
|
512
|
+
SERVICE: 'WMS', REQUEST: 'GetFeatureInfo', VERSION: '1.3.0',
|
|
513
|
+
INFO_FORMAT: 'application/json', STYLES: '', FEATURE_COUNT: 1
|
|
514
|
+
}, fi.params || {});
|
|
515
|
+
const key = String(p.VERSION).indexOf('1.1') === 0 ? 'SRS' : 'CRS';
|
|
516
|
+
delete p.SRS; delete p.CRS;
|
|
517
|
+
p[key] = fi.projection || 'EPSG:3857';
|
|
518
|
+
p.LAYERS = fi.layers;
|
|
519
|
+
p.QUERY_LAYERS = fi.queryLayers || fi.layers;
|
|
520
|
+
p.WIDTH = 1; p.HEIGHT = 1; p.I = 0; p.J = 0; p.X = 0; p.Y = 0; // I/J is 1.3.0, X/Y is 1.1.1
|
|
521
|
+
p.BBOX = [c[0] - d, c[1] - d, c[0] + d, c[1] + d].join(',');
|
|
522
|
+
return query(fi.url, p);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Band value in a GetFeatureInfo response.
|
|
527
|
+
*
|
|
528
|
+
* The band's property name is not standard - GeoServer calls it GRAY_INDEX for a
|
|
529
|
+
* single-band coverage, but a styled or renamed layer answers otherwise. Without an
|
|
530
|
+
* explicit `property` the first finite number wins, which is right whenever the coverage
|
|
531
|
+
* carries one band, and is why `property` exists for when it does not.
|
|
532
|
+
*/
|
|
533
|
+
function bandValue(body, property) {
|
|
534
|
+
const f = body && body.features && body.features[0];
|
|
535
|
+
const props = f && f.properties;
|
|
536
|
+
if (!props) return null;
|
|
537
|
+
if (property) { const v = Number(props[property]); return isFinite(v) ? v : null; }
|
|
538
|
+
for (const k of Object.keys(props)) { const v = Number(props[k]); if (props[k] !== null && props[k] !== '' && isFinite(v)) return v; }
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** Web Mercator pixel coordinates at zoom `z`, origin at the top-left corner of the world. */
|
|
543
|
+
function worldPixel(lon, lat, z, tileSize) {
|
|
544
|
+
const n = tileSize * Math.pow(2, z);
|
|
545
|
+
const s = Math.sin(lat * Math.PI / 180);
|
|
546
|
+
return [(lon + 180) / 360 * n, (0.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * n];
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Reads elevations from a set of terrain tiles.
|
|
551
|
+
*
|
|
552
|
+
* Positions are held in **world pixels** rather than tile by tile: the four neighbours
|
|
553
|
+
* of a point can fall in two different tiles whenever it runs along an edge, which is
|
|
554
|
+
* the common case on a track. Converting to world pixels first, then resolving the
|
|
555
|
+
* tile, makes the edge case disappear instead of handling it.
|
|
556
|
+
*/
|
|
557
|
+
class DemSampler {
|
|
558
|
+
/** @param {Object} cfg `url`, `encoding`, `tileSize`, `concurrency`. */
|
|
559
|
+
constructor(cfg) {
|
|
560
|
+
this.cfg = cfg;
|
|
561
|
+
this.decode = (typeof cfg.encoding === 'function') ? cfg.encoding
|
|
562
|
+
: (DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium);
|
|
563
|
+
this.tileUrl = tileUrlFn(cfg);
|
|
564
|
+
this.tiles = new Map(); // "z/x/y" -> RGBA pixels, or null if the tile was lost
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* North-west neighbour of the point plus the interpolation fractions, in world pixels.
|
|
569
|
+
*
|
|
570
|
+
* The half-pixel subtracted is not a fudge: pixel centres fall on half-integers, and
|
|
571
|
+
* without that shift `floor()` would return the cell containing the point rather than
|
|
572
|
+
* its western neighbour, offsetting the whole profile by half a pixel.
|
|
573
|
+
*/
|
|
574
|
+
_neighbours(lon, lat, z) {
|
|
575
|
+
const wp = worldPixel(lon, lat, z, this.cfg.tileSize);
|
|
576
|
+
const px = wp[0] - 0.5, py = wp[1] - 0.5;
|
|
577
|
+
const i0 = Math.floor(px), j0 = Math.floor(py);
|
|
578
|
+
return { i0, j0, tx: px - i0, ty: py - j0 };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** Tile key of a world pixel; x wraps around the globe, y clamps at the poles. */
|
|
582
|
+
_key(i, j, z) {
|
|
583
|
+
const ts = this.cfg.tileSize, span = ts * Math.pow(2, z);
|
|
584
|
+
const jj = Math.min(span - 1, Math.max(0, j)), ii = ((i % span) + span) % span;
|
|
585
|
+
return { key: z + '/' + Math.floor(ii / ts) + '/' + Math.floor(jj / ts), ii, jj };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Elevation of one pixel, or null if its tile is missing. */
|
|
589
|
+
_at(i, j, z) {
|
|
590
|
+
const ts = this.cfg.tileSize;
|
|
591
|
+
const r = this._key(i, j, z);
|
|
592
|
+
const data = this.tiles.get(r.key);
|
|
593
|
+
if (!data) return null;
|
|
594
|
+
const o = ((r.jj % ts) * ts + (r.ii % ts)) * 4;
|
|
595
|
+
const v = this.decode(data[o], data[o + 1], data[o + 2], data[o + 3]);
|
|
596
|
+
return (v == null || !isFinite(v)) ? null : v;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Elevation **bilinearly interpolated** between the four surrounding pixels; null as
|
|
601
|
+
* soon as a single one is missing.
|
|
602
|
+
*
|
|
603
|
+
* Bilinear rather than "the pixel containing the point": on a 30 or 90 m model, taking
|
|
604
|
+
* the pixel value makes the profile advance in stairs, and every stair counts as a
|
|
605
|
+
* climb then a descent in the ascent total. The interpolation invents no relief — it
|
|
606
|
+
* renders the same surface, without the steps of the sampling grid.
|
|
607
|
+
*/
|
|
608
|
+
sample(lon, lat, z) {
|
|
609
|
+
const n = this._neighbours(lon, lat, z);
|
|
610
|
+
const a = this._at(n.i0, n.j0, z), b = this._at(n.i0 + 1, n.j0, z);
|
|
611
|
+
const c = this._at(n.i0, n.j0 + 1, z), d = this._at(n.i0 + 1, n.j0 + 1, z);
|
|
612
|
+
if (a == null || b == null || c == null || d == null) return null;
|
|
613
|
+
const north = a + (b - a) * n.tx, south = c + (d - c) * n.tx;
|
|
614
|
+
return north + (south - north) * n.ty;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Keys of the tiles needed by the four neighbours of each of the points. */
|
|
618
|
+
tilesFor(lonlats, z) {
|
|
619
|
+
const keys = new Set();
|
|
620
|
+
for (const ll of lonlats) {
|
|
621
|
+
const n = this._neighbours(ll[0], ll[1], z);
|
|
622
|
+
for (let di = 0; di < 2; di++) for (let dj = 0; dj < 2; dj++) keys.add(this._key(n.i0 + di, n.j0 + dj, z).key);
|
|
623
|
+
}
|
|
624
|
+
return keys;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** Pixels of one tile, or null if it could not be read. */
|
|
628
|
+
_fetch(key) {
|
|
629
|
+
const parts = key.split('/');
|
|
630
|
+
const url = this.tileUrl(+parts[0], +parts[1], +parts[2]);
|
|
631
|
+
return new Promise((resolve) => {
|
|
632
|
+
const img = new Image();
|
|
633
|
+
// Without this attribute the canvas is tainted and getImageData throws: the tile
|
|
634
|
+
// would display, but stay unreadable. The intended sources answer with
|
|
635
|
+
// Access-Control-Allow-Origin: *.
|
|
636
|
+
img.crossOrigin = 'anonymous';
|
|
637
|
+
img.onload = () => {
|
|
638
|
+
try {
|
|
639
|
+
const ts = this.cfg.tileSize;
|
|
640
|
+
const cv = document.createElement('canvas');
|
|
641
|
+
cv.width = ts; cv.height = ts;
|
|
642
|
+
const ctx = cv.getContext('2d', { willReadFrequently: true });
|
|
643
|
+
ctx.drawImage(img, 0, 0, ts, ts);
|
|
644
|
+
resolve(ctx.getImageData(0, 0, ts, ts).data);
|
|
645
|
+
} catch (e) { resolve(null); }
|
|
646
|
+
};
|
|
647
|
+
img.onerror = () => resolve(null);
|
|
648
|
+
img.src = url;
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Loads the missing tiles, `concurrency` in flight. Resolves false if one is missing.
|
|
654
|
+
*
|
|
655
|
+
* Lost tiles are remembered as such: without that, a second pass over the same track
|
|
656
|
+
* would fire the same requests, doomed to fail again.
|
|
657
|
+
*/
|
|
658
|
+
load(keys) {
|
|
659
|
+
const todo = Array.from(keys).filter((k) => !this.tiles.has(k));
|
|
660
|
+
let next = 0, ok = true;
|
|
661
|
+
const worker = () => {
|
|
662
|
+
if (next >= todo.length) return Promise.resolve();
|
|
663
|
+
const k = todo[next++];
|
|
664
|
+
return this._fetch(k).then((data) => { this.tiles.set(k, data); if (!data) ok = false; return worker(); });
|
|
665
|
+
};
|
|
666
|
+
const lanes = [];
|
|
667
|
+
for (let i = 0; i < Math.min(this.cfg.concurrency, todo.length); i++) lanes.push(worker());
|
|
668
|
+
return Promise.all(lanes).then(() => ok);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* The `dem` option (true | source name | sampling function | object) → a full
|
|
674
|
+
* configuration, or null.
|
|
675
|
+
*
|
|
676
|
+
* A `sample` function short-circuits the tile machinery entirely: the application
|
|
677
|
+
* answers with the elevations itself, from wherever it can reach them - a GeoServer
|
|
678
|
+
* WCS coverage, a GeoTIFF decoded with geotiff.js, a national elevation API. Only the
|
|
679
|
+
* transport is delegated; the control keeps the sequencing, the all-or-nothing rule,
|
|
680
|
+
* the spinner and the `demload` event, which is where the subtle parts live.
|
|
681
|
+
*
|
|
682
|
+
* That extension point rather than a WMS/WCS/GeoTIFF mode per protocol: reading a
|
|
683
|
+
* GeoTIFF means a full decoder, and this library has no runtime dependency to spend
|
|
684
|
+
* on one that most users would never load.
|
|
685
|
+
*/
|
|
686
|
+
function demConfig(opt) {
|
|
687
|
+
if (!opt) return null;
|
|
688
|
+
if (typeof opt === 'function') return Object.assign({}, DEM_DEFAULTS, { sample: opt });
|
|
689
|
+
const raw = (opt === true || typeof opt === 'string') ? { source: opt === true ? 'terrarium' : opt } : Object.assign({}, opt);
|
|
690
|
+
if (typeof raw.sample === 'function') return Object.assign({}, DEM_DEFAULTS, raw);
|
|
691
|
+
// A point-query source: no tile grid, no pixel decoding.
|
|
692
|
+
if (raw.featureInfo) {
|
|
693
|
+
const fiCfg = Object.assign({}, DEM_DEFAULTS, raw);
|
|
694
|
+
fiCfg.sample = featureInfoSampler(fiCfg);
|
|
695
|
+
return fiCfg;
|
|
696
|
+
}
|
|
697
|
+
// An ol/source/DataTile (GeoTIFF above all) carries values, not URLs: its own path.
|
|
698
|
+
if (raw.olSource && typeof raw.olSource.getTileUrlFunction !== 'function' &&
|
|
699
|
+
typeof raw.olSource.getTile === 'function') {
|
|
700
|
+
const dtCfg = Object.assign({}, DEM_DEFAULTS, raw);
|
|
701
|
+
dtCfg.sample = dataTileSampler(dtCfg);
|
|
702
|
+
return dtCfg;
|
|
703
|
+
}
|
|
704
|
+
// Tiles: an OpenLayers source or a WMS both stand in for the url template.
|
|
705
|
+
const hasTiles = raw.url || raw.wms || raw.olSource;
|
|
706
|
+
const preset = DEM_PRESETS[raw.source] || (hasTiles ? {} : DEM_PRESETS.terrarium);
|
|
707
|
+
const cfg = Object.assign({}, DEM_DEFAULTS, preset, raw);
|
|
708
|
+
if (cfg.api === 'ign') { cfg.sample = ignSampler(cfg); return cfg; } // a point API
|
|
709
|
+
return (cfg.url || cfg.wms || cfg.olSource) ? cfg : null;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* Zoom at which to download the model: the finest one that fits within `maxTiles`.
|
|
714
|
+
*
|
|
715
|
+
* It is the tiling that widens as the track grows, not a model that degrades: a 10 km
|
|
716
|
+
* track is read at the finest step available, a 300 km one at a coarser step rather
|
|
717
|
+
* than in three hundred requests.
|
|
718
|
+
*/
|
|
719
|
+
function demZoomFor(sampler, lonlats, cfg) {
|
|
720
|
+
if (typeof cfg.zoom === 'number') return cfg.zoom;
|
|
721
|
+
for (let z = cfg.maxZoom; z > 0; z--) if (sampler.tilesFor(lonlats, z).size <= cfg.maxTiles) return z;
|
|
722
|
+
return 1;
|
|
723
|
+
}
|
|
724
|
+
|
|
156
725
|
// =======================================================================
|
|
157
726
|
/**
|
|
158
727
|
* @typedef {Object} ElevationProfileOptions
|
|
@@ -186,6 +755,7 @@ import * as d3 from 'd3';
|
|
|
186
755
|
* @property {boolean} [responsive=true] Adapt width/placement; mobile included.
|
|
187
756
|
* @property {number} [mobileBreakpoint=640] Below this width: mobile mode (100% width, top/bottom only).
|
|
188
757
|
* @property {boolean} [zoom=false] A/B buttons to crop map + profile to a sub-range.
|
|
758
|
+
* @property {boolean} [exportPng=false] Toolbar button exporting the whole panel as a PNG.
|
|
189
759
|
* @property {boolean} [ignoreStops=true] When computing time, ignore stopped segments (moving time).
|
|
190
760
|
* @property {number} [stopSpeed=0.5] Speed threshold (m/s) below which a segment counts as a stop.
|
|
191
761
|
* @property {Array<'distance'|'elevation'|'slope'|'time'>} [tooltipItems=['distance','elevation']] Tooltip content (`'time'` = elapsed time at the cursor, if the track has time data).
|
|
@@ -194,6 +764,16 @@ import * as d3 from 'd3';
|
|
|
194
764
|
* @property {?string} [titleLink=null] Feature property holding a URL → clickable title.
|
|
195
765
|
* @property {number} [maxPoints=2000] Decimation for render/interaction (stats use full data).
|
|
196
766
|
* @property {?import('ol/proj/Projection').default|string} [dataProjection=null] Projection of the feature coordinates.
|
|
767
|
+
* @property {?(boolean|string|Function|Object)} [dem='terrarium'] Fill missing elevations
|
|
768
|
+
* from a terrain model. Sources: `'terrarium'` (default) or `true` = AWS Terrain Tiles;
|
|
769
|
+
* `'ign'` = IGN Géoplateforme RGE ALTI (France, keyless, `apiKey` optional);
|
|
770
|
+
* `{url}` = XYZ template; `{wms:{url,layers,params}}` = WMS tiles;
|
|
771
|
+
* `{olSource}` = any `ol/source/TileImage` (XYZ, TileWMS, …);
|
|
772
|
+
* `{featureInfo:{url,layers,property}}` = WMS GetFeatureInfo, one request per point,
|
|
773
|
+
* for a greyscale coverage that cannot be decoded from its pixels (slow);
|
|
774
|
+
* a function or `{sample}` `(lonlats, ctx) => number[]|Promise<number[]>` to source them
|
|
775
|
+
* yourself; `null` disables the whole thing.
|
|
776
|
+
* Decoding: `encoding` is `'terrarium'`, `'mapbox'`, or a function `(r,g,b,a) => metres`.
|
|
197
777
|
*/
|
|
198
778
|
|
|
199
779
|
/**
|
|
@@ -221,12 +801,13 @@ import * as d3 from 'd3';
|
|
|
221
801
|
this._marker = null;
|
|
222
802
|
this._collapsed = !!o.collapsed;
|
|
223
803
|
this._cropMode = false; this._zoomA = null; this._zoomB = null; this._armed = null; this._fitRes = null;
|
|
804
|
+
this._demZ = null; this._demFor = null; this._demSeq = 0; this._demLoading = false;
|
|
224
805
|
this._onResize = () => { if (this._feature && !this._collapsed) this._render(); };
|
|
225
806
|
this._buildDom(element);
|
|
226
807
|
element.style.display = 'none';
|
|
227
808
|
}
|
|
228
809
|
|
|
229
|
-
// ----------
|
|
810
|
+
// ---------- static helpers ----------------------------------------
|
|
230
811
|
/**
|
|
231
812
|
* Whether a feature has any Z (elevation) coordinate.
|
|
232
813
|
* @param {import('ol/Feature').default} feature
|
|
@@ -235,8 +816,7 @@ import * as d3 from 'd3';
|
|
|
235
816
|
static featureHasZ(feature) {
|
|
236
817
|
const g = feature && feature.getGeometry && feature.getGeometry();
|
|
237
818
|
if (!g) return false;
|
|
238
|
-
const
|
|
239
|
-
for (const seg of coords) for (const c of seg) if (c.length > 2 && isFinite(c[2])) return true;
|
|
819
|
+
for (const seg of geomLines(g)) for (const c of seg) if (c.length > 2 && isFinite(c[2])) return true;
|
|
240
820
|
return false;
|
|
241
821
|
}
|
|
242
822
|
|
|
@@ -248,8 +828,7 @@ import * as d3 from 'd3';
|
|
|
248
828
|
static featureHasTime(feature) {
|
|
249
829
|
const g = feature && feature.getGeometry && feature.getGeometry();
|
|
250
830
|
if (!g) return false;
|
|
251
|
-
|
|
252
|
-
return !!extractTimes(feature, lines);
|
|
831
|
+
return !!extractTimes(feature, geomLines(g));
|
|
253
832
|
}
|
|
254
833
|
|
|
255
834
|
// ---------- DOM ---------------------------------------------------
|
|
@@ -275,6 +854,8 @@ import * as d3 from 'd3';
|
|
|
275
854
|
this._btnA = mkBtn('oep-a', ICON_A, o.labels.zoomStart, () => this._arm('A'));
|
|
276
855
|
this._btnB = mkBtn('oep-b', ICON_B, o.labels.zoomEnd, () => this._arm('B'));
|
|
277
856
|
this._btnAll = mkBtn('oep-all', ICON_ALL, o.labels.zoomAll, () => this._exitZoom());
|
|
857
|
+
// Last of the toolbar, so it sits to the right of the zoom buttons.
|
|
858
|
+
this._btnPng = mkBtn('oep-png', ICON_PNG, o.labels.exportPng, () => this.exportPNG());
|
|
278
859
|
header.appendChild(this._toolbar);
|
|
279
860
|
|
|
280
861
|
const btn = document.createElement('button');
|
|
@@ -338,7 +919,7 @@ import * as d3 from 'd3';
|
|
|
338
919
|
this._adjustAttribution();
|
|
339
920
|
}
|
|
340
921
|
|
|
341
|
-
// ---------- responsive
|
|
922
|
+
// ---------- responsive --------------------------------------------
|
|
342
923
|
_availWidth() {
|
|
343
924
|
const map = this.getMap();
|
|
344
925
|
const t = map && map.getTargetElement && map.getTargetElement();
|
|
@@ -354,7 +935,7 @@ import * as d3 from 'd3';
|
|
|
354
935
|
return mobile;
|
|
355
936
|
}
|
|
356
937
|
|
|
357
|
-
//
|
|
938
|
+
// Lift the OL attribution above the profile when the profile takes the bottom-right corner
|
|
358
939
|
_adjustAttribution() {
|
|
359
940
|
const map = this.getMap();
|
|
360
941
|
const target = map && map.getTargetElement && map.getTargetElement();
|
|
@@ -365,17 +946,17 @@ import * as d3 from 'd3';
|
|
|
365
946
|
const mapR = target.getBoundingClientRect();
|
|
366
947
|
const pR = this.element.getBoundingClientRect();
|
|
367
948
|
if (!pR.height) return;
|
|
368
|
-
const bottomGap = mapR.bottom - pR.bottom; //
|
|
949
|
+
const bottomGap = mapR.bottom - pR.bottom; // map bottom edge <-> profile bottom
|
|
369
950
|
const rightGap = mapR.right - pR.right;
|
|
370
|
-
const atBottom = bottomGap < pR.height; //
|
|
371
|
-
const reachesRight = rightGap < 24; //
|
|
951
|
+
const atBottom = bottomGap < pR.height; // profile sits in the bottom band
|
|
952
|
+
const reachesRight = rightGap < 24; // reaches the bottom-right corner (attributions)
|
|
372
953
|
if (atBottom && reachesRight) {
|
|
373
954
|
attr.style.right = `${Math.max(0, Math.round(rightGap))}px`;
|
|
374
|
-
attr.style.bottom = `${Math.round(pR.height + 2 * bottomGap)}px`; //
|
|
955
|
+
attr.style.bottom = `${Math.round(pR.height + 2 * bottomGap)}px`; // same gap above the profile
|
|
375
956
|
}
|
|
376
957
|
}
|
|
377
958
|
|
|
378
|
-
// ----------
|
|
959
|
+
// ---------- map ---------------------------------------------------
|
|
379
960
|
setMap(map) {
|
|
380
961
|
const prev = this.getMap();
|
|
381
962
|
super.setMap(map);
|
|
@@ -394,7 +975,7 @@ import * as d3 from 'd3';
|
|
|
394
975
|
if (typeof window !== 'undefined') window.addEventListener('resize', this._onResize);
|
|
395
976
|
|
|
396
977
|
const lineAt = (pixel) => map.forEachFeatureAtPixel(pixel, (f) => {
|
|
397
|
-
const g = f.getGeometry(); return (g
|
|
978
|
+
const g = f.getGeometry(); return isProfilable(g) ? f : undefined;
|
|
398
979
|
});
|
|
399
980
|
|
|
400
981
|
this._mapKeys = [];
|
|
@@ -404,11 +985,11 @@ import * as d3 from 'd3';
|
|
|
404
985
|
if (o.hideOnMapClick) this._mapKeys.push(map.on('click', (evt) => { if (!lineAt(evt.pixel) && this._feature) this.clear(); }));
|
|
405
986
|
if (o.followMap) this._mapKeys.push(map.on('pointermove', (evt) => {
|
|
406
987
|
if (!this._feature || this._collapsed) return;
|
|
407
|
-
const cp = this.
|
|
988
|
+
const cp = this._closestOnProfile(evt.coordinate); if (!cp) return;
|
|
408
989
|
const px = map.getPixelFromCoordinate(cp); if (!px) return;
|
|
409
990
|
if (Math.hypot(px[0] - evt.pixel[0], px[1] - evt.pixel[1]) < 14) this._focusByCoord(cp); else this._clearFocus();
|
|
410
991
|
}));
|
|
411
|
-
//
|
|
992
|
+
// leave the A/B crop when the map is zoomed out
|
|
412
993
|
this._mapKeys.push(map.on('moveend', () => {
|
|
413
994
|
if (this._cropMode && this._fitRes && map.getView().getResolution() > this._fitRes * 1.25) this._exitZoom();
|
|
414
995
|
}));
|
|
@@ -417,7 +998,8 @@ import * as d3 from 'd3';
|
|
|
417
998
|
|
|
418
999
|
// ---------- API ---------------------------------------------------
|
|
419
1000
|
/**
|
|
420
|
-
* Show the profile for the given feature (LineString
|
|
1001
|
+
* Show the profile for the given feature (LineString, MultiLineString, or a Polygon /
|
|
1002
|
+
* MultiPolygon profiled along its outer ring), ideally 3D.
|
|
421
1003
|
* Passing a falsy value hides the control.
|
|
422
1004
|
* @param {?import('ol/Feature').default} feature
|
|
423
1005
|
* @returns {this}
|
|
@@ -425,17 +1007,21 @@ import * as d3 from 'd3';
|
|
|
425
1007
|
setFeature(feature) {
|
|
426
1008
|
this._feature = feature || null;
|
|
427
1009
|
this._cropMode = false; this._zoomA = null; this._zoomB = null; this._armed = null;
|
|
428
|
-
if (!feature) { this._fullSamples = this._samples = null; this._clear(); return this; }
|
|
1010
|
+
if (!feature) { this._fullSamples = this._samples = null; this._demZ = this._demFor = null; this._clear(); return this; }
|
|
429
1011
|
this.element.style.display = '';
|
|
430
1012
|
this._compute();
|
|
1013
|
+
// Before the render, not after: it is _fillFromDem that knows whether a fill is
|
|
1014
|
+
// starting, and the render needs that to draw the spinner instead of a flat profile.
|
|
1015
|
+
this._fillFromDem(feature);
|
|
431
1016
|
this._updateZoomButtons();
|
|
432
|
-
if (
|
|
1017
|
+
if (this._collapsed) this._renderTitle(); else this._render();
|
|
433
1018
|
return this;
|
|
434
1019
|
}
|
|
435
1020
|
/** Hide the profile and clear the current feature. @returns {this} */
|
|
436
1021
|
clear() { return this.setFeature(null); }
|
|
437
1022
|
/**
|
|
438
|
-
* @returns {?{distance:number,ascent:number,descent:number,min:number,max:number,maxAbsSlope:number,points:number}}
|
|
1023
|
+
* @returns {?{distance:number,duration:?number,ascent:number,descent:number,min:number,max:number,maxAbsSlope:number,points:number}}
|
|
1024
|
+
* `duration` is `null` when the track carries no time data.
|
|
439
1025
|
*/
|
|
440
1026
|
getStats() { return this._stats; }
|
|
441
1027
|
/** @param {string|Object} t Theme name or colors object. @returns {this} */
|
|
@@ -454,22 +1040,125 @@ import * as d3 from 'd3';
|
|
|
454
1040
|
if (patch && (patch.theme || 'color' in patch)) this._applyTheme();
|
|
455
1041
|
if (patch && ('transparency' in patch || 'transparencyLevel' in patch)) this._applyTransparency();
|
|
456
1042
|
if (patch && 'collapsable' in patch) this._applyCollapsable();
|
|
457
|
-
if (patch && 'zoom' in patch) this._updateZoomButtons();
|
|
1043
|
+
if (patch && ('zoom' in patch || 'exportPng' in patch)) this._updateZoomButtons();
|
|
458
1044
|
if (patch && typeof patch.width !== 'undefined' && typeof patch.width === 'number') this.options.width = patch.width;
|
|
459
|
-
if (
|
|
1045
|
+
if (patch && 'dem' in patch) { this._demZ = null; this._demFor = null; }
|
|
1046
|
+
if (this._feature) { this._compute(); this._fillFromDem(this._feature); this._updateZoomButtons(); if (this._collapsed) this._renderTitle(); else this._render(); }
|
|
460
1047
|
return this;
|
|
461
1048
|
}
|
|
462
1049
|
|
|
463
|
-
// ----------
|
|
1050
|
+
// ---------- digital elevation model -------------------------------
|
|
1051
|
+
/**
|
|
1052
|
+
* Fills the missing elevations from a terrain model, then redraws.
|
|
1053
|
+
*
|
|
1054
|
+
* **A track is filled entirely or not at all.** A profile missing a few points is not
|
|
1055
|
+
* an incomplete profile: points without Z count as zero, the line dives to sea level
|
|
1056
|
+
* and the ascent total becomes absurd. Better the flat profile we would have had
|
|
1057
|
+
* without the DEM.
|
|
1058
|
+
*
|
|
1059
|
+
* Nothing is reported to the user on failure — the fill is a supplement, it has no
|
|
1060
|
+
* business breaking a display that succeeded without it. The `demload` event lets the
|
|
1061
|
+
* application know if it wants to.
|
|
1062
|
+
*
|
|
1063
|
+
* @param {import('ol/Feature').default} feature
|
|
1064
|
+
* @fires demload
|
|
1065
|
+
* @private
|
|
1066
|
+
*/
|
|
1067
|
+
_fillFromDem(feature) {
|
|
1068
|
+
const cfg = demConfig(this.options.dem);
|
|
1069
|
+
if (!cfg || !feature || this._demFor === feature) return;
|
|
1070
|
+
if (ElevationProfile.featureHasZ(feature)) return; // the track already carries its Z
|
|
1071
|
+
// Canvas decoding needs a browser; a `sample` function does not, and must stay
|
|
1072
|
+
// usable where there is no DOM.
|
|
1073
|
+
if (!cfg.sample && (typeof Image === 'undefined' || typeof document === 'undefined')) return;
|
|
1074
|
+
|
|
1075
|
+
const geom = feature.getGeometry && feature.getGeometry();
|
|
1076
|
+
if (!geom) return;
|
|
1077
|
+
const lines = geomLines(geom);
|
|
1078
|
+
const dataProj = this.options.dataProjection || (this.getMap() && this.getMap().getView().getProjection()) || 'EPSG:3857';
|
|
1079
|
+
const lonlats = [];
|
|
1080
|
+
for (const seg of lines) for (const c of seg) lonlats.push(toLonLat(c, dataProj));
|
|
1081
|
+
if (!lonlats.length) return;
|
|
1082
|
+
|
|
1083
|
+
// Sequence number: a track clicked while another is loading must win, otherwise the
|
|
1084
|
+
// slowest response would overwrite the profile on screen.
|
|
1085
|
+
const seq = ++this._demSeq;
|
|
1086
|
+
this._demLoading = true;
|
|
1087
|
+
|
|
1088
|
+
// A misconfigured source must not take the profile down with it. _fillFromDem runs
|
|
1089
|
+
// inside setFeature, so anything thrown here would reach the caller and leave no
|
|
1090
|
+
// chart at all - where the whole point is that the fill is a supplement.
|
|
1091
|
+
try {
|
|
1092
|
+
this._startFill(cfg, seq, feature, lonlats, dataProj);
|
|
1093
|
+
} catch (e) {
|
|
1094
|
+
this._demDone(seq, feature, null, lonlats.length, null, 0);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/** @private */
|
|
1099
|
+
_startFill(cfg, seq, feature, lonlats, dataProj) {
|
|
1100
|
+
if (cfg.sample) {
|
|
1101
|
+
// Wrapped in a promise chain so a function that throws synchronously fails the
|
|
1102
|
+
// same way as one that rejects - a source that misbehaves must not leave the
|
|
1103
|
+
// spinner turning forever.
|
|
1104
|
+
Promise.resolve()
|
|
1105
|
+
.then(() => cfg.sample(lonlats, { feature, projection: dataProj }))
|
|
1106
|
+
.then((zs) => this._demDone(seq, feature, zs, lonlats.length, null, 0))
|
|
1107
|
+
.catch(() => this._demDone(seq, feature, null, lonlats.length, null, 0));
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
const sampler = new DemSampler(cfg);
|
|
1112
|
+
const z = demZoomFor(sampler, lonlats, cfg);
|
|
1113
|
+
sampler.load(sampler.tilesFor(lonlats, z)).then((ok) => {
|
|
1114
|
+
const zs = ok ? lonlats.map((ll) => sampler.sample(ll[0], ll[1], z)) : null;
|
|
1115
|
+
this._demDone(seq, feature, zs, lonlats.length, z, sampler.tiles.size);
|
|
1116
|
+
}).catch(() => this._demDone(seq, feature, null, lonlats.length, z, 0));
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/**
|
|
1120
|
+
* Outcome of a fill, whatever produced it: adopt the elevations, drop the spinner,
|
|
1121
|
+
* redraw, announce.
|
|
1122
|
+
*
|
|
1123
|
+
* A result of the wrong length is refused outright rather than padded. Elevations one
|
|
1124
|
+
* can no longer map to their points are worse than absent ones: they would land on the
|
|
1125
|
+
* wrong places, and nothing downstream would notice.
|
|
1126
|
+
*
|
|
1127
|
+
* @fires demload
|
|
1128
|
+
* @private
|
|
1129
|
+
*/
|
|
1130
|
+
_demDone(seq, feature, zs, expected, zoom, tiles) {
|
|
1131
|
+
// A newer fill has taken over: it owns _demLoading and will clear it itself.
|
|
1132
|
+
if (seq !== this._demSeq || this._feature !== feature) return;
|
|
1133
|
+
const usable = Array.isArray(zs) && zs.length === expected && zs.every((v) => v != null && isFinite(v));
|
|
1134
|
+
this._demLoading = false;
|
|
1135
|
+
if (usable) { this._demZ = zs; this._demFor = feature; this._compute(); }
|
|
1136
|
+
// Redrawn even on failure: the spinner has to give way to the flat profile.
|
|
1137
|
+
this._updateZoomButtons();
|
|
1138
|
+
if (!this._collapsed) this._render();
|
|
1139
|
+
/**
|
|
1140
|
+
* Fired once a terrain-model fill has completed (or failed).
|
|
1141
|
+
* @event demload
|
|
1142
|
+
* @property {boolean} ok Whether every point could be sampled.
|
|
1143
|
+
* @property {?number} zoom Tile zoom level used, `null` for a custom sampler.
|
|
1144
|
+
* @property {number} tiles Tiles fetched, `0` for a custom sampler.
|
|
1145
|
+
*/
|
|
1146
|
+
this.dispatchEvent({ type: 'demload', ok: usable, zoom, tiles });
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// ---------- computation -------------------------------------------
|
|
464
1150
|
_compute() {
|
|
465
1151
|
const o = this.options;
|
|
466
1152
|
const geom = this._feature.getGeometry();
|
|
467
|
-
const lines =
|
|
1153
|
+
const lines = geomLines(geom);
|
|
468
1154
|
const dataProj = o.dataProjection || (this.getMap() && this.getMap().getView().getProjection()) || 'EPSG:3857';
|
|
469
1155
|
|
|
1156
|
+
// Terrain-model elevations, if they were loaded for THIS feature.
|
|
1157
|
+
const demZ = (this._demFor === this._feature) ? this._demZ : null;
|
|
1158
|
+
|
|
470
1159
|
const times = extractTimes(this._feature, lines);
|
|
471
1160
|
this._hasTime = !!times;
|
|
472
|
-
const ignoreStops = o.ignoreStops !== false; //
|
|
1161
|
+
const ignoreStops = o.ignoreStops !== false; // default: stops are excluded
|
|
473
1162
|
const stopSpeed = (o.stopSpeed != null ? o.stopSpeed : 0.5); // m/s
|
|
474
1163
|
const pts = [];
|
|
475
1164
|
let cum = 0, prev = null, i = -1, tAcc = 0, prevMs = null;
|
|
@@ -482,13 +1171,14 @@ import * as d3 from 'd3';
|
|
|
482
1171
|
if (times && times[i] != null) {
|
|
483
1172
|
const ms = times[i];
|
|
484
1173
|
if (prevMs != null) {
|
|
485
|
-
const dt = (ms - prevMs) / 1000; //
|
|
1174
|
+
const dt = (ms - prevMs) / 1000; // seconds over the segment
|
|
486
1175
|
if (dt > 0 && (!ignoreStops || (dseg / dt) >= stopSpeed)) tAcc += dt;
|
|
487
1176
|
}
|
|
488
1177
|
t = tAcc; prevMs = ms;
|
|
489
1178
|
}
|
|
490
1179
|
prev = ll;
|
|
491
|
-
|
|
1180
|
+
const z = (c.length > 2 && isFinite(c[2])) ? c[2] : (demZ ? demZ[i] : 0);
|
|
1181
|
+
pts.push({ x: cum, z, coord: c, t });
|
|
492
1182
|
}
|
|
493
1183
|
if (o.smoothing > 0) this._smooth(pts, o.smoothing);
|
|
494
1184
|
|
|
@@ -508,11 +1198,13 @@ import * as d3 from 'd3';
|
|
|
508
1198
|
const distance = samples.length ? samples[samples.length - 1].x - samples[0].x : 0;
|
|
509
1199
|
const ta = samples.length ? samples[0].t : null, tb = samples.length ? samples[samples.length - 1].t : null;
|
|
510
1200
|
const duration = (ta != null && tb != null) ? (tb - ta) : null;
|
|
1201
|
+
// Reported for a closed ring too, where they are equal by construction: on a loop,
|
|
1202
|
+
// D+ is exactly the figure one is after.
|
|
511
1203
|
return { distance, duration, ascent, descent, min: isFinite(zmin) ? zmin : 0, max: isFinite(zmax) ? zmax : 0, maxAbsSlope: maxAbs, points: samples.length };
|
|
512
1204
|
}
|
|
513
1205
|
_smooth(pts, meters) {
|
|
514
1206
|
if (!(meters > 0) || pts.length < 3) return;
|
|
515
|
-
const half = meters / 2; //
|
|
1207
|
+
const half = meters / 2; // window = +/-(meters/2) along the track
|
|
516
1208
|
const z = pts.map((p) => p.z);
|
|
517
1209
|
let lo = 0, hi = 0, sum = 0;
|
|
518
1210
|
for (let i = 0; i < pts.length; i++) {
|
|
@@ -537,20 +1229,20 @@ import * as d3 from 'd3';
|
|
|
537
1229
|
if (samples.length) samples[0].slope = samples.length > 1 ? samples[1].slope : 0;
|
|
538
1230
|
}
|
|
539
1231
|
|
|
540
|
-
// ----------
|
|
1232
|
+
// ---------- slope: colours ----------------------------------------
|
|
541
1233
|
_slopeScale() {
|
|
542
1234
|
const cs = this.options.slopeClassSize || 2.5;
|
|
543
1235
|
const maxClasses = this.options.maxClasses || 8;
|
|
544
1236
|
const realIdx = Math.max(1, Math.floor((this._stats.maxAbsSlope || 0) / cs));
|
|
545
|
-
const maxIdx = Math.min(realIdx, maxClasses - 1); //
|
|
546
|
-
const capped = realIdx > maxIdx; //
|
|
1237
|
+
const maxIdx = Math.min(realIdx, maxClasses - 1); // at most `maxClasses` classes (default 8)
|
|
1238
|
+
const capped = realIdx > maxIdx; // some slopes overflow the last class
|
|
547
1239
|
let colorByIndex;
|
|
548
1240
|
if (this.slopeColors && this.slopeColors.length) {
|
|
549
1241
|
const interp = d3.interpolateRgbBasis(this.slopeColors);
|
|
550
1242
|
colorByIndex = (idx) => interp(maxIdx ? idx / maxIdx : 0);
|
|
551
1243
|
} else {
|
|
552
|
-
//
|
|
553
|
-
//
|
|
1244
|
+
// Ramp with non-uniform stops: the cold end (blue-green, hard to read) is squeezed,
|
|
1245
|
+
// PURE yellow in the middle, then orange, red. Class 0 = blue, top class = red.
|
|
554
1246
|
const ramp = d3.scaleLinear()
|
|
555
1247
|
.domain([0, 0.16, 0.42, 0.68, 1])
|
|
556
1248
|
.range(['#2166ac', '#27a35a', '#ffe000', '#f4791f', '#d7191c'])
|
|
@@ -562,8 +1254,8 @@ import * as d3 from 'd3';
|
|
|
562
1254
|
}
|
|
563
1255
|
_classIndex(slope, sc) { return Math.min(sc.maxIdx, Math.floor(Math.abs(slope) / sc.classSize)); }
|
|
564
1256
|
|
|
565
|
-
// ----------
|
|
566
|
-
// 7 sec
|
|
1257
|
+
// ---------- time: adaptive format ---------------------------------
|
|
1258
|
+
// 7 sec | 26 min | 1 h 48 min | 2 d 3 h (days + hours normalised)
|
|
567
1259
|
_fmtDuration(sec) {
|
|
568
1260
|
if (sec == null || !isFinite(sec)) return '';
|
|
569
1261
|
const u = (this.options.labels && this.options.labels.durationUnits) || { s: 'sec', m: 'min', h: 'h', d: 'j' };
|
|
@@ -580,14 +1272,35 @@ import * as d3 from 'd3';
|
|
|
580
1272
|
return h ? `${d} ${u.d} ${h} ${u.h}` : `${d} ${u.d}`;
|
|
581
1273
|
}
|
|
582
1274
|
|
|
583
|
-
// ----------
|
|
584
|
-
|
|
585
|
-
|
|
1275
|
+
// ---------- header + legend ---------------------------------------
|
|
1276
|
+
/**
|
|
1277
|
+
* Track title, and its optional link.
|
|
1278
|
+
*
|
|
1279
|
+
* Its own method because it is the only part of the header that stays visible once
|
|
1280
|
+
* collapsed — the CSS hides the body, the stats, the legend and the toolbar. `_render`
|
|
1281
|
+
* is skipped while collapsed, so without a separate entry point the title would keep
|
|
1282
|
+
* naming the previous track after a change of feature.
|
|
1283
|
+
*/
|
|
1284
|
+
_renderTitle() {
|
|
1285
|
+
const o = this.options, f = this._feature;
|
|
1286
|
+
if (!f) return;
|
|
586
1287
|
const name = (f.get && f.get(o.titleProperty)) || 'Profil';
|
|
587
1288
|
const linkUrl = o.titleLink && f.get && f.get(o.titleLink);
|
|
588
1289
|
if (isUrl(linkUrl)) this._titleEl.innerHTML = `<a href="${esc(linkUrl)}" target="_blank" rel="noopener">${esc(name)}</a>`;
|
|
589
1290
|
else this._titleEl.textContent = name;
|
|
590
1291
|
this._titleEl.setAttribute('title', name);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
_renderHeader() {
|
|
1295
|
+
const o = this.options, s = this._stats, f = this._feature;
|
|
1296
|
+
this._renderTitle();
|
|
1297
|
+
// While the elevations are still unknown, every figure would read zero: a D+ of 0 m
|
|
1298
|
+
// then jumping to 1 200 is worse than no figure at all.
|
|
1299
|
+
if (this._demLoading) {
|
|
1300
|
+
this._statsEl.innerHTML = ''; this._statsEl.removeAttribute('title');
|
|
1301
|
+
this._legendEl.innerHTML = ''; this._legendEl.style.display = 'none';
|
|
1302
|
+
return;
|
|
1303
|
+
}
|
|
591
1304
|
|
|
592
1305
|
const html = [], text = [];
|
|
593
1306
|
o.headerItems.forEach((it) => {
|
|
@@ -623,18 +1336,40 @@ import * as d3 from 'd3';
|
|
|
623
1336
|
} else this._legendEl.style.display = 'none';
|
|
624
1337
|
}
|
|
625
1338
|
|
|
626
|
-
|
|
1339
|
+
/**
|
|
1340
|
+
* Spinner shown in place of the chart while the terrain model loads.
|
|
1341
|
+
*
|
|
1342
|
+
* It keeps the chart's height so the panel does not jump when the profile replaces it,
|
|
1343
|
+
* and it carries no colour of its own: the CSS takes `--oep-area`, which `_applyTheme`
|
|
1344
|
+
* has just set - the theme colour, or the track colour under `color: 'auto'`.
|
|
1345
|
+
*/
|
|
1346
|
+
_renderSpinner() {
|
|
1347
|
+
const H = typeof this.options.height === 'number' ? this.options.height : 180;
|
|
1348
|
+
this._body.innerHTML = '';
|
|
1349
|
+
const box = document.createElement('div');
|
|
1350
|
+
box.className = 'oep-loading';
|
|
1351
|
+
box.style.height = `${H}px`;
|
|
1352
|
+
box.setAttribute('role', 'status');
|
|
1353
|
+
box.setAttribute('aria-label', this.options.labels.loading);
|
|
1354
|
+
const sp = document.createElement('div');
|
|
1355
|
+
sp.className = 'oep-spinner';
|
|
1356
|
+
box.appendChild(sp);
|
|
1357
|
+
this._body.appendChild(box);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// ---------- rendering ---------------------------------------------
|
|
627
1361
|
_render() {
|
|
628
1362
|
const o = this.options, s = this._stats, data = this._samples;
|
|
629
1363
|
if (!data || !data.length) return;
|
|
630
1364
|
this._applyTheme();
|
|
631
1365
|
const mobile = this._applyPlacement();
|
|
632
1366
|
this._renderHeader();
|
|
1367
|
+
if (this._demLoading) { this._renderSpinner(); return; }
|
|
633
1368
|
|
|
634
1369
|
const m = o.margins, u = m.unit || 'px';
|
|
635
1370
|
const toPx = (v) => u === 'px' ? v : v * (parseFloat(getComputedStyle(this.element).fontSize) || 16);
|
|
636
1371
|
|
|
637
|
-
//
|
|
1372
|
+
// Width: 100% on mobile; 'auto'/'100%'/'full' = map width; otherwise a number capped to the map
|
|
638
1373
|
const avail = this._availWidth();
|
|
639
1374
|
const isAuto = (o.width === 'auto' || o.width === '100%' || o.width === 'full');
|
|
640
1375
|
const desktopW = isAuto ? avail : Math.min(typeof o.width === 'number' ? o.width : (parseFloat(o.width) || avail), avail);
|
|
@@ -671,7 +1406,7 @@ import * as d3 from 'd3';
|
|
|
671
1406
|
const cls = this._classIndex(data[i].slope, sc);
|
|
672
1407
|
let j = i; while (j + 1 < data.length && this._classIndex(data[j + 1].slope, sc) === cls) j++;
|
|
673
1408
|
g.append('path').datum(data.slice(i - 1, j + 1)).attr('class', 'oep-area-slope').attr('fill', sc.colorByIndex(cls)).attr('d', areaGen);
|
|
674
|
-
if (i > 1) seps.push(data[i - 1]); //
|
|
1409
|
+
if (i > 1) seps.push(data[i - 1]); // a class change is a boundary
|
|
675
1410
|
i = j + 1;
|
|
676
1411
|
}
|
|
677
1412
|
if (o.slopeSeparators) seps.forEach((d) => {
|
|
@@ -687,7 +1422,7 @@ import * as d3 from 'd3';
|
|
|
687
1422
|
g.append('text').attr('class', 'oep-axis-label').attr('x', innerW).attr('y', innerH + mb - 4).attr('text-anchor', 'end').text(distAxisLabel(o.units));
|
|
688
1423
|
g.append('g').attr('class', 'oep-axis oep-axis-y').call(d3.axisLeft(y).ticks(yTicks).tickFormat((d) => o.units === 'imperial' ? Math.round(d * 3.28084) : d));
|
|
689
1424
|
|
|
690
|
-
//
|
|
1425
|
+
// A / B markers while a range is being picked
|
|
691
1426
|
if (o.zoom && !this._cropMode) {
|
|
692
1427
|
[['A', this._zoomA], ['B', this._zoomB]].forEach(([nm, val]) => {
|
|
693
1428
|
if (val == null) return;
|
|
@@ -722,11 +1457,147 @@ import * as d3 from 'd3';
|
|
|
722
1457
|
this._adjustAttribution();
|
|
723
1458
|
}
|
|
724
1459
|
|
|
1460
|
+
// ---------- PNG export ---------------------------------------------
|
|
1461
|
+
/**
|
|
1462
|
+
* Properties frozen onto the exported clone.
|
|
1463
|
+
*
|
|
1464
|
+
* A serialized SVG carries no stylesheet: rules that live in the CSS file, and every
|
|
1465
|
+
* `var(--oep-*)` they resolve, vanish the moment the markup leaves the document. The
|
|
1466
|
+
* export would come out as black shapes on nothing. So the computed value of each
|
|
1467
|
+
* painting property is written inline, node by node.
|
|
1468
|
+
*/
|
|
1469
|
+
static get _EXPORT_PROPS() {
|
|
1470
|
+
return ['fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-dasharray',
|
|
1471
|
+
'stroke-linecap', 'stroke-linejoin', 'opacity', 'font-family', 'font-size',
|
|
1472
|
+
'font-weight', 'text-anchor', 'shape-rendering'];
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/** Copies the computed painting styles of `src` onto `dst`, recursively. */
|
|
1476
|
+
_freezeStyles(src, dst) {
|
|
1477
|
+
const props = ElevationProfile._EXPORT_PROPS;
|
|
1478
|
+
const cs = getComputedStyle(src);
|
|
1479
|
+
let inline = '';
|
|
1480
|
+
for (const p of props) { const v = cs.getPropertyValue(p); if (v) inline += `${p}:${v};`; }
|
|
1481
|
+
dst.setAttribute('style', inline);
|
|
1482
|
+
const a = src.children, b = dst.children;
|
|
1483
|
+
for (let i = 0; i < a.length && i < b.length; i++) this._freezeStyles(a[i], b[i]);
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
/**
|
|
1487
|
+
* The whole panel as an SVG string: background, title, stats, legend, chart.
|
|
1488
|
+
*
|
|
1489
|
+
* Rebuilt rather than screenshotted. The header is HTML and the chart is SVG, and the
|
|
1490
|
+
* only way to put HTML in an SVG is a `foreignObject`, which browsers refuse to
|
|
1491
|
+
* rasterise consistently. Redrawing the two text lines as `<text>` is a handful of
|
|
1492
|
+
* lines and works everywhere.
|
|
1493
|
+
*
|
|
1494
|
+
* The current-position indicator is dropped: it marks where the pointer happens to be,
|
|
1495
|
+
* which means nothing once the image is saved.
|
|
1496
|
+
*/
|
|
1497
|
+
_exportSvg() {
|
|
1498
|
+
const chart = this._body.querySelector('svg');
|
|
1499
|
+
if (!chart) return null;
|
|
1500
|
+
const cs = getComputedStyle(this.element);
|
|
1501
|
+
const bg = cs.getPropertyValue('--oep-bg').trim() || '#fff';
|
|
1502
|
+
const fg = cs.getPropertyValue('--oep-text').trim() || '#222';
|
|
1503
|
+
const font = cs.fontFamily || 'system-ui, sans-serif';
|
|
1504
|
+
const W = +chart.getAttribute('width'), H = +chart.getAttribute('height');
|
|
1505
|
+
const pad = 8, titleH = 20, statsH = this._statsEl.textContent ? 15 : 0;
|
|
1506
|
+
const legend = (this._legendEl.style.display !== 'none') ? this._legendEl : null;
|
|
1507
|
+
const legH = legend ? 18 : 0;
|
|
1508
|
+
const top = pad + titleH + statsH + legH;
|
|
1509
|
+
|
|
1510
|
+
const clone = chart.cloneNode(true);
|
|
1511
|
+
// The pointer indicator and the hit-test overlay have no place in a saved image.
|
|
1512
|
+
clone.querySelectorAll('.oep-focus, .oep-overlay').forEach((n) => n.remove());
|
|
1513
|
+
this._freezeStyles(chart, clone);
|
|
1514
|
+
// width/height are kept: a nested <svg> without them fills the parent viewport, so
|
|
1515
|
+
// the chart would be stretched over the header's height as well.
|
|
1516
|
+
|
|
1517
|
+
const esc2 = (t) => esc(String(t));
|
|
1518
|
+
const parts = [];
|
|
1519
|
+
parts.push(`<rect width="${W + 2 * pad}" height="${H + top + pad}" fill="${esc2(bg)}"/>`);
|
|
1520
|
+
parts.push(`<text x="${pad}" y="${pad + 13}" style="font-family:${esc2(font)};font-size:13px;font-weight:600;fill:${esc2(fg)}">${esc2(this._titleEl.textContent)}</text>`);
|
|
1521
|
+
if (statsH) parts.push(`<text x="${pad}" y="${pad + titleH + 10}" style="font-family:${esc2(font)};font-size:11px;fill:${esc2(fg)};opacity:.85">${esc2(this._statsEl.textContent)}</text>`);
|
|
1522
|
+
if (legend) {
|
|
1523
|
+
let x = pad;
|
|
1524
|
+
const y = pad + titleH + statsH + 12;
|
|
1525
|
+
for (const item of legend.querySelectorAll('.oep-leg-it')) {
|
|
1526
|
+
const sw = item.querySelector('.oep-sw');
|
|
1527
|
+
const color = sw ? getComputedStyle(sw).backgroundColor : 'none';
|
|
1528
|
+
const label = item.textContent.trim();
|
|
1529
|
+
parts.push(`<rect x="${x}" y="${y - 8}" width="10" height="10" fill="${esc2(color)}"/>`);
|
|
1530
|
+
parts.push(`<text x="${x + 14}" y="${y}" style="font-family:${esc2(font)};font-size:10px;fill:${esc2(fg)}">${esc2(label)}</text>`);
|
|
1531
|
+
x += 14 + label.length * 5.6 + 10;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
parts.push(`<g transform="translate(${pad},${top})">${new XMLSerializer().serializeToString(clone)}</g>`);
|
|
1535
|
+
return {
|
|
1536
|
+
width: W + 2 * pad, height: H + top + pad,
|
|
1537
|
+
svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${W + 2 * pad}" height="${H + top + pad}" ` +
|
|
1538
|
+
`viewBox="0 0 ${W + 2 * pad} ${H + top + pad}">${parts.join('')}</svg>`
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* Export the whole panel - title, stats, legend and chart - as a PNG.
|
|
1544
|
+
*
|
|
1545
|
+
* Resolves with the Blob. Unless `download` is false, it also saves the file, which is
|
|
1546
|
+
* what the toolbar button does.
|
|
1547
|
+
*
|
|
1548
|
+
* @param {{scale?:number, filename?:string, download?:boolean}} [opts]
|
|
1549
|
+
* `scale` defaults to the device pixel ratio, so the image is not soft on a retina
|
|
1550
|
+
* screen. `filename` defaults to the track title.
|
|
1551
|
+
* @returns {Promise<Blob>}
|
|
1552
|
+
*/
|
|
1553
|
+
exportPNG(opts) {
|
|
1554
|
+
const o = opts || {};
|
|
1555
|
+
const built = this._exportSvg();
|
|
1556
|
+
if (!built) return Promise.reject(new Error('ol-elevation-profile: nothing to export'));
|
|
1557
|
+
const scale = o.scale || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
|
|
1558
|
+
return new Promise((resolve, reject) => {
|
|
1559
|
+
const img = new Image();
|
|
1560
|
+
img.onload = () => {
|
|
1561
|
+
try {
|
|
1562
|
+
const cv = document.createElement('canvas');
|
|
1563
|
+
cv.width = Math.round(built.width * scale);
|
|
1564
|
+
cv.height = Math.round(built.height * scale);
|
|
1565
|
+
const ctx = cv.getContext('2d');
|
|
1566
|
+
ctx.scale(scale, scale);
|
|
1567
|
+
ctx.drawImage(img, 0, 0);
|
|
1568
|
+
cv.toBlob((blob) => {
|
|
1569
|
+
if (!blob) { reject(new Error('ol-elevation-profile: PNG encoding failed')); return; }
|
|
1570
|
+
if (o.download !== false) this._save(blob, o.filename);
|
|
1571
|
+
resolve(blob);
|
|
1572
|
+
}, 'image/png');
|
|
1573
|
+
} catch (e) { reject(e); }
|
|
1574
|
+
};
|
|
1575
|
+
img.onerror = () => reject(new Error('ol-elevation-profile: SVG could not be rasterised'));
|
|
1576
|
+
// Encoded as a data URL rather than a blob: URL - a blob: source taints the canvas
|
|
1577
|
+
// in some browsers, and toBlob would then throw a security error.
|
|
1578
|
+
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(built.svg);
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
/** @private */
|
|
1583
|
+
_save(blob, filename) {
|
|
1584
|
+
const name = filename || `${(this._titleEl.textContent || 'profile').replace(/[\\/:*?"<>|]+/g, '-').trim()}.png`;
|
|
1585
|
+
const url = URL.createObjectURL(blob);
|
|
1586
|
+
const a = document.createElement('a');
|
|
1587
|
+
a.href = url; a.download = name;
|
|
1588
|
+
document.body.appendChild(a); a.click(); a.remove();
|
|
1589
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
1590
|
+
}
|
|
1591
|
+
|
|
725
1592
|
// ---------- zoom A/B ----------------------------------------------
|
|
726
1593
|
_arm(which) { this._armed = (this._armed === which) ? null : which; this._updateZoomButtons(); if (this._focus) this._render(); }
|
|
727
1594
|
_updateZoomButtons() {
|
|
728
|
-
const
|
|
729
|
-
|
|
1595
|
+
const o = this.options, has = !!this._feature;
|
|
1596
|
+
const show = !!o.zoom && has;
|
|
1597
|
+
const png = !!o.exportPng && has;
|
|
1598
|
+
// The toolbar carries both: it stays visible as long as either has something to show.
|
|
1599
|
+
this._toolbar.style.display = (show || png) ? '' : 'none';
|
|
1600
|
+
this._btnPng.style.display = png ? '' : 'none';
|
|
730
1601
|
const crop = this._cropMode;
|
|
731
1602
|
this._btnA.style.display = show && !crop ? '' : 'none';
|
|
732
1603
|
this._btnB.style.display = show && !crop ? '' : 'none';
|
|
@@ -760,6 +1631,29 @@ import * as d3 from 'd3';
|
|
|
760
1631
|
if (map && this._feature) map.getView().fit(this._feature.getGeometry().getExtent(), { padding: [40, 40, 40, 40], duration: 400 });
|
|
761
1632
|
}
|
|
762
1633
|
|
|
1634
|
+
/**
|
|
1635
|
+
* Point of the profiled outline closest to a map coordinate.
|
|
1636
|
+
*
|
|
1637
|
+
* A polygon's own `getClosestPoint` answers for its **surface**: with the cursor inside
|
|
1638
|
+
* the ring it returns the cursor itself, so the marker would follow the pointer across
|
|
1639
|
+
* the whole shape instead of sliding along the outline. Lines keep the geometry's own
|
|
1640
|
+
* answer, which is exact rather than limited to the decimated samples.
|
|
1641
|
+
*/
|
|
1642
|
+
_closestOnProfile(coordinate) {
|
|
1643
|
+
const g = this._feature && this._feature.getGeometry();
|
|
1644
|
+
if (!g) return null;
|
|
1645
|
+
if (!/Polygon/.test(g.getType())) return g.getClosestPoint(coordinate);
|
|
1646
|
+
const data = this._fullSamples;
|
|
1647
|
+
if (!data || !data.length) return null;
|
|
1648
|
+
let best = null, bd = Infinity;
|
|
1649
|
+
for (const p of data) {
|
|
1650
|
+
const dx = p.coord[0] - coordinate[0], dy = p.coord[1] - coordinate[1];
|
|
1651
|
+
const dd = dx * dx + dy * dy;
|
|
1652
|
+
if (dd < bd) { bd = dd; best = p.coord; }
|
|
1653
|
+
}
|
|
1654
|
+
return best;
|
|
1655
|
+
}
|
|
1656
|
+
|
|
763
1657
|
// ---------- focus -------------------------------------------------
|
|
764
1658
|
_tooltipText(d) {
|
|
765
1659
|
const o = this.options, parts = [];
|
|
@@ -797,7 +1691,7 @@ import * as d3 from 'd3';
|
|
|
797
1691
|
this._legendEl.innerHTML = ''; this._legendEl.style.display = 'none';
|
|
798
1692
|
this._titleEl.textContent = this.options.labels.empty; this._titleEl.removeAttribute('title');
|
|
799
1693
|
this._statsEl.innerHTML = ''; this._statsEl.removeAttribute('title');
|
|
800
|
-
this._cropMode = false; this._updateZoomButtons();
|
|
1694
|
+
this._cropMode = false; this._demLoading = false; this._updateZoomButtons();
|
|
801
1695
|
this._clearFocus();
|
|
802
1696
|
this.element.style.display = 'none';
|
|
803
1697
|
this._adjustAttribution();
|
|
@@ -811,6 +1705,9 @@ import * as d3 from 'd3';
|
|
|
811
1705
|
*/
|
|
812
1706
|
ElevationProfile.addTheme = (name, colors) => { THEMES[name] = colors; };
|
|
813
1707
|
ElevationProfile.THEMES = THEMES;
|
|
1708
|
+
/** Known keyless terrain-tile sources, keyed by `dem.source` name. */
|
|
1709
|
+
ElevationProfile.DEM_PRESETS = DEM_PRESETS;
|
|
1710
|
+
ElevationProfile.DemSampler = DemSampler;
|
|
814
1711
|
ElevationProfile.POSITIONS = POSITIONS;
|
|
815
1712
|
ElevationProfile.version = '0.6.0';
|
|
816
1713
|
|