ol-elevation-profile 1.0.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.
@@ -2,7 +2,8 @@
2
2
  import Control from 'ol/control/Control.js';
3
3
  import Overlay from 'ol/Overlay.js';
4
4
  import { unByKey } from 'ol/Observable.js';
5
- import { toLonLat } from 'ol/proj.js';
5
+ import { toLonLat, get, transform, fromLonLat } from 'ol/proj.js';
6
+ import TileState from 'ol/TileState.js';
6
7
  import { getDistance } from 'ol/sphere.js';
7
8
  import { boundingExtent } from 'ol/extent.js';
8
9
  import * as d3 from 'd3';
@@ -69,6 +70,7 @@ import * as d3 from 'd3';
69
70
  responsive: true, // adapts width/placement, mobile included
70
71
  mobileBreakpoint: 640, // <= screen width -> mobile mode (100% width, top/bottom)
71
72
  zoom: false, // start/end buttons cropping map + profile to A..B
73
+ exportPng: false, // toolbar button exporting the panel as a PNG
72
74
  ignoreStops: true, // duration = moving time (stops excluded)
73
75
  stopSpeed: 0.5, // stop threshold in m/s (~1.8 km/h)
74
76
  tooltipItems: ['distance', 'elevation'],
@@ -81,6 +83,7 @@ import * as d3 from 'd3';
81
83
  time: 'Temps', duration: 'Durée',
82
84
  durationUnits: { s: 'sec', m: 'min', h: 'h', d: 'j' },
83
85
  zoomStart: 'Définir le début (A)', zoomEnd: 'Définir la fin (B)', zoomAll: 'Tout voir',
86
+ exportPng: 'Exporter en PNG',
84
87
  loading: 'Chargement du profil altimétrique'
85
88
  }
86
89
  };
@@ -186,6 +189,7 @@ import * as d3 from 'd3';
186
189
  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>';
187
190
  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>';
188
191
  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>';
192
+ 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>';
189
193
  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>';
190
194
 
191
195
  // ----- digital elevation model (DEM) -----------------------------------
@@ -208,17 +212,335 @@ import * as d3 from 'd3';
208
212
  encoding: 'terrarium',
209
213
  maxZoom: 14,
210
214
  attributions: 'Elevation: <a href="https://registry.opendata.aws/terrain-tiles/">Terrain Tiles</a> (AWS Open Data)'
215
+ },
216
+ /**
217
+ * IGN Géoplateforme, serving the RGE ALTI over France and its overseas territories.
218
+ *
219
+ * A point API rather than tiles, hence its own sampler: it answers 200 points per
220
+ * request and announces one request per second, so a 10 000 point track takes about
221
+ * fifty calls spread over as many seconds. In exchange it is metre-accurate where the
222
+ * world models are at ninety.
223
+ *
224
+ * **No key is required** on the public endpoint - verified against the live service.
225
+ * `apiKey` exists for a deployment that does demand one; it is appended as a query
226
+ * parameter, named by `apiKeyParam`.
227
+ *
228
+ * Outside its coverage the service does not error: it answers OUT_OF_COVERAGE for the
229
+ * point. No border is coded here - one asks, and it says itself where it does not know.
230
+ */
231
+ ign: {
232
+ api: 'ign',
233
+ url: 'https://data.geopf.fr/altimetrie/1.0/calcul/alti/rest/elevation.json',
234
+ resource: 'ign_rge_alti_wld',
235
+ batch: 200, // more fits, but the URL grows ~20 bytes a point and hits 414
236
+ minInterval: 1100, // ms between calls; the service announces 1 req/s
237
+ attributions: 'Elevation: <a href="https://geoservices.ign.fr/rgealti">RGE ALTI</a> (IGN)'
211
238
  }
212
239
  };
213
240
 
241
+ /** Value the IGN service returns where it holds no measurement. */
242
+ const IGN_NO_DATA = -99999;
243
+
244
+ /**
245
+ * Request URL for one batch, in the order given: the response returns the elevations in
246
+ * the same one.
247
+ *
248
+ * `zonly=true` cuts the response down to the elevations alone, without echoing the
249
+ * coordinates - a third of the weight for the same information. Coordinates rounded to
250
+ * the millionth of a degree, about ten centimetres: beyond that one only adds digits to
251
+ * the URL.
252
+ */
253
+ function ignUrl(cfg, pts) {
254
+ const f = (v) => v.toFixed(6);
255
+ const sep = cfg.url.indexOf('?') >= 0 ? '&' : '?';
256
+ let u = cfg.url + sep + 'resource=' + encodeURIComponent(cfg.resource) +
257
+ '&delimiter=|&zonly=true' +
258
+ '&lon=' + pts.map((p) => f(p[0])).join('|') +
259
+ '&lat=' + pts.map((p) => f(p[1])).join('|');
260
+ if (cfg.apiKey) u += '&' + (cfg.apiKeyParam || 'apikey') + '=' + encodeURIComponent(cfg.apiKey);
261
+ return u;
262
+ }
263
+
264
+ /**
265
+ * Sampler for the IGN service: batches, paces, and maps out-of-coverage to null.
266
+ *
267
+ * A batch whose response does not carry exactly as many elevations as points were asked
268
+ * for fails the whole fill. Elevations one can no longer map to their points are worse
269
+ * than absent ones: they would land on the wrong places, silently.
270
+ */
271
+ function ignSampler(cfg) {
272
+ const size = Math.max(1, cfg.batch || 200);
273
+ const gap = cfg.minInterval || 0;
274
+ return (lonlats) => {
275
+ const out = [];
276
+ let last = 0;
277
+ const step = (i) => {
278
+ if (i >= lonlats.length) return Promise.resolve(out);
279
+ const chunk = lonlats.slice(i, i + size);
280
+ const wait = Math.max(0, gap - (Date.now() - last));
281
+ return new Promise((r) => setTimeout(r, wait))
282
+ .then(() => { last = Date.now(); return fetch(ignUrl(cfg, chunk)); })
283
+ .then((r) => (r && r.ok) ? r.json() : null)
284
+ .then((body) => {
285
+ const z = body && body.elevations;
286
+ if (!Array.isArray(z) || z.length !== chunk.length) return null;
287
+ for (const v of z) out.push((v == null || v <= IGN_NO_DATA) ? null : v);
288
+ return step(i + size);
289
+ });
290
+ };
291
+ return step(0);
292
+ };
293
+ }
294
+
214
295
  const DEM_DEFAULTS = { source: 'terrarium', zoom: 'auto', maxZoom: 14, maxTiles: 32, concurrency: 6, tileSize: 256 };
215
296
 
216
- /** RGB → metres decoders, one per encoding convention. */
297
+ /**
298
+ * RGB → metres decoders, one per encoding convention.
299
+ *
300
+ * `encoding` also takes a function `(r, g, b, a) => metres`, for a tile set that packs
301
+ * elevation its own way. Return null where the pixel carries no measurement: the fill is
302
+ * abandoned rather than guessed.
303
+ *
304
+ * A GeoServer greyscale DEM is NOT decoded here. What a WMS returns is a rendered image,
305
+ * stretched and quantised by its style, not the coverage values; reading it back would
306
+ * be reading the rendering. Those go through `featureInfo`, which asks the server for the
307
+ * band value itself (see demConfig).
308
+ */
217
309
  const DEM_DECODERS = {
218
310
  terrarium: (r, g, b) => (r * 256 + g + b / 256) - 32768,
219
311
  mapbox: (r, g, b) => -1e4 + (r * 65536 + g * 256 + b) * 0.1
220
312
  };
221
313
 
314
+ /** Half the Web Mercator world, in metres: the bound of EPSG:3857. */
315
+ const MERC_HALF = 20037508.342789244;
316
+
317
+ /** Extent of an XYZ tile in EPSG:3857, for the WMS requests built below. */
318
+ function tileExtent(z, x, y) {
319
+ const span = 2 * MERC_HALF / Math.pow(2, z);
320
+ const minX = -MERC_HALF + x * span, maxY = MERC_HALF - y * span;
321
+ return [minX, maxY - span, minX + span, maxY];
322
+ }
323
+
324
+ function query(base, params) {
325
+ const sep = base.indexOf('?') >= 0 ? '&' : '?';
326
+ return base.replace(/[?&]$/, '') + sep +
327
+ Object.keys(params).map((k) => k + '=' + encodeURIComponent(params[k])).join('&');
328
+ }
329
+
330
+ /**
331
+ * WMS GetMap URL covering one XYZ tile, so a WMS behaves like any other tile source.
332
+ *
333
+ * The axis-order trap: WMS 1.3.0 names the reference system `CRS`, 1.1.1 names it `SRS`,
334
+ * and sending the wrong one gets the request rejected or silently mis-georeferenced.
335
+ * The version actually in force decides, after the caller's params are merged in.
336
+ */
337
+ function wmsTileUrl(w, z, x, y, tileSize) {
338
+ const p = Object.assign({
339
+ SERVICE: 'WMS', REQUEST: 'GetMap', VERSION: '1.3.0', FORMAT: 'image/png',
340
+ TRANSPARENT: 'false', STYLES: ''
341
+ }, w.params || {});
342
+ const key = String(p.VERSION).indexOf('1.1') === 0 ? 'SRS' : 'CRS';
343
+ delete p.SRS; delete p.CRS;
344
+ p[key] = w.projection || 'EPSG:3857';
345
+ p.LAYERS = w.layers;
346
+ p.WIDTH = tileSize; p.HEIGHT = tileSize;
347
+ p.BBOX = tileExtent(z, x, y).join(',');
348
+ return query(w.url, p);
349
+ }
350
+
351
+ /**
352
+ * Where a tile comes from: an OpenLayers source, a WMS, or an XYZ template.
353
+ *
354
+ * Handing an `ol/source/TileImage` (XYZ, TileWMS, or any subclass) delegates URL building
355
+ * to OpenLayers itself, which already knows that source's quirks - subdomains, custom
356
+ * params, tile grid. Cheaper and safer than reimplementing each one here.
357
+ */
358
+ function tileUrlFn(cfg) {
359
+ const src = cfg.olSource;
360
+ if (src && typeof src.getTileUrlFunction === 'function') {
361
+ const fn = src.getTileUrlFunction();
362
+ const proj = get('EPSG:3857');
363
+ return (z, x, y) => fn([z, x, y], 1, proj);
364
+ }
365
+ if (cfg.wms) return (z, x, y) => wmsTileUrl(cfg.wms, z, x, y, cfg.tileSize);
366
+ return (z, x, y) => cfg.url.replace('{z}', z).replace('{x}', x).replace('{y}', y);
367
+ }
368
+
369
+ /**
370
+ * Values of one DataTile, or null if it never arrived.
371
+ *
372
+ * A DataTile carries no URL: it is loaded by the source itself and its values are read
373
+ * back with getData(). The state has to be watched rather than awaited - OpenLayers
374
+ * announces it through a `change` event, not a promise.
375
+ */
376
+ function loadDataTile(tile) {
377
+ return new Promise((resolve) => {
378
+ const settle = () => {
379
+ const st = tile.getState();
380
+ if (st === TileState.LOADED) { resolve(tile.getData ? tile.getData() : null); return true; }
381
+ if (st === TileState.ERROR || st === TileState.EMPTY) { resolve(null); return true; }
382
+ return false;
383
+ };
384
+ if (settle()) return;
385
+ const onChange = () => { if (settle()) tile.removeEventListener('change', onChange); };
386
+ tile.addEventListener('change', onChange);
387
+ if (tile.load) tile.load();
388
+ });
389
+ }
390
+
391
+ /**
392
+ * Sampler for an `ol/source/DataTile` - `ol/source/GeoTIFF` above all.
393
+ *
394
+ * Its own path because such a source shares nothing with the XYZ one: no URL, no Web
395
+ * Mercator, no 256 pixel tiles. A GeoTIFF keeps **its own projection and its own tile
396
+ * grid**, both only known once `getView()` has resolved, and its values are real numbers
397
+ * rather than colours - so nothing here goes through a decoder.
398
+ *
399
+ * Positions are held in grid pixels, as with the XYZ tiles and for the same reason: the
400
+ * four neighbours of a point straddle two tiles as soon as it runs along an edge.
401
+ *
402
+ * `normalize: false` matters on the source, otherwise OpenLayers rescales the values to
403
+ * 0..1 and the profile comes out in fractions of nothing.
404
+ */
405
+ function dataTileSampler(cfg) {
406
+ const src = cfg.olSource;
407
+ const band = cfg.band || 0;
408
+ return (lonlats) => {
409
+ // getView() is only awaited when the grid is not known yet - which is the GeoTIFF
410
+ // case, where it settles once the metadata has been read. On a plain DataTile that
411
+ // promise never settles at all, and awaiting it unconditionally hangs the fill.
412
+ const known = src.getTileGrid && src.getTileGrid();
413
+ const ready = known ? Promise.resolve(null) : Promise.resolve(src.getView ? src.getView() : null);
414
+ return ready.then((view) => {
415
+ const grid = known || (src.getTileGrid && src.getTileGrid()) || (view && view.tileGrid);
416
+ if (!grid) return null;
417
+ const proj = get((view && view.projection) || (src.getProjection && src.getProjection()) || 'EPSG:3857');
418
+ const zs = grid.getResolutions ? grid.getResolutions().length - 1 : 0;
419
+ const bands = src.bandCount || 1;
420
+ const coords = lonlats.map((ll) => transform([ll[0], ll[1]], 'EPSG:4326', proj));
421
+
422
+ // Finest level whose tile count stays within maxTiles, as for the XYZ tiles: it is
423
+ // the tiling that widens with the track, not the model that degrades.
424
+ // Pixel bounds of the coverage, when it declares an extent. A point inside the raster
425
+ // but within half a pixel of its edge lands on a neighbour that does not exist: its
426
+ // tile would come back empty and the all-or-nothing rule would drop the whole track.
427
+ // Half a pixel of tolerance at the borders, as on any regular grid.
428
+ const ext = (grid.getExtent && grid.getExtent()) || (view && view.extent) || null;
429
+ const plan = (z) => {
430
+ const res = grid.getResolution(z), origin = grid.getOrigin(z);
431
+ let ts = grid.getTileSize(z); ts = Array.isArray(ts) ? ts : [ts, ts];
432
+ const cols = ext ? Math.round((ext[2] - ext[0]) / res) : Infinity;
433
+ const rows = ext ? Math.round((ext[3] - ext[1]) / res) : Infinity;
434
+ const clampI = (i) => Math.min(cols - 1, Math.max(0, i));
435
+ const clampJ = (j) => Math.min(rows - 1, Math.max(0, j));
436
+ const need = new Map();
437
+ const at = coords.map((c) => {
438
+ const px = (c[0] - origin[0]) / res - 0.5, py = (origin[1] - c[1]) / res - 0.5;
439
+ const i0 = clampI(Math.floor(px)), j0 = clampJ(Math.floor(py));
440
+ for (let di = 0; di < 2; di++) for (let dj = 0; dj < 2; dj++) {
441
+ const tx = Math.floor(clampI(i0 + di) / ts[0]), ty = Math.floor(clampJ(j0 + dj) / ts[1]);
442
+ need.set(tx + '/' + ty, [tx, ty]);
443
+ }
444
+ // Interpolation fractions clamped too: a point beyond the last pixel centre keeps
445
+ // that pixel's value rather than extrapolating past the edge of the data.
446
+ return { i0, j0, tx: Math.min(1, Math.max(0, px - i0)), ty: Math.min(1, Math.max(0, py - j0)), clampI, clampJ };
447
+ });
448
+ return { res, origin, ts, need, at, clampI, clampJ };
449
+ };
450
+ let z = zs, p = plan(z);
451
+ while (z > 0 && p.need.size > cfg.maxTiles) { z--; p = plan(z); }
452
+ if (p.need.size > cfg.maxTiles) return null;
453
+
454
+ const keys = Array.from(p.need.keys());
455
+ return Promise.all(keys.map((k) => {
456
+ const t = p.need.get(k);
457
+ return loadDataTile(src.getTile(z, t[0], t[1], 1, proj)).then((d) => [k, d]);
458
+ })).then((pairs) => {
459
+ const tiles = new Map(pairs);
460
+ const value = (i, j) => {
461
+ const tx = Math.floor(p.clampI(i) / p.ts[0]), ty = Math.floor(p.clampJ(j) / p.ts[1]);
462
+ i = p.clampI(i); j = p.clampJ(j);
463
+ const d = tiles.get(tx + '/' + ty);
464
+ if (!d) return null;
465
+ const col = i - tx * p.ts[0], row = j - ty * p.ts[1];
466
+ const v = d[(row * p.ts[0] + col) * bands + band];
467
+ return (v == null || !isFinite(v)) ? null : v;
468
+ };
469
+ return p.at.map((n) => {
470
+ const a = value(n.i0, n.j0), b = value(n.i0 + 1, n.j0);
471
+ const c = value(n.i0, n.j0 + 1), e = value(n.i0 + 1, n.j0 + 1);
472
+ if (a == null || b == null || c == null || e == null) return null;
473
+ const north = a + (b - a) * n.tx, south = c + (e - c) * n.tx;
474
+ return north + (south - north) * n.ty;
475
+ });
476
+ });
477
+ });
478
+ };
479
+ }
480
+
481
+ /**
482
+ * WMS GetFeatureInfo sampler: one request per point, for a coverage served as a rendered
483
+ * greyscale that cannot be decoded from its pixels.
484
+ *
485
+ * **It is slow**, unavoidably: a thousand-point track is a thousand round trips, where a
486
+ * tile source needs a handful. Worth it only when nothing else can reach the data - and
487
+ * `concurrency` is what keeps it bearable.
488
+ */
489
+ function featureInfoSampler(cfg) {
490
+ const fi = cfg.featureInfo;
491
+ const lanes = Math.max(1, cfg.concurrency || 6);
492
+ return (lonlats) => {
493
+ const out = new Array(lonlats.length);
494
+ let next = 0, broken = false;
495
+ const one = () => {
496
+ if (broken || next >= lonlats.length) return Promise.resolve();
497
+ const i = next++;
498
+ return fetch(featureInfoUrl(fi, lonlats[i]))
499
+ .then((r) => (r && r.ok) ? r.json() : null)
500
+ .then((body) => { out[i] = bandValue(body, fi.property); return one(); })
501
+ .catch(() => { broken = true; });
502
+ };
503
+ const running = [];
504
+ for (let i = 0; i < Math.min(lanes, lonlats.length); i++) running.push(one());
505
+ return Promise.all(running).then(() => broken ? null : out);
506
+ };
507
+ }
508
+
509
+ /** GetFeatureInfo URL for one point: a one-pixel image centred on it. */
510
+ function featureInfoUrl(fi, ll) {
511
+ const c = fromLonLat([ll[0], ll[1]]);
512
+ const d = fi.resolution || 1; // half-size of the box, in metres
513
+ const p = Object.assign({
514
+ SERVICE: 'WMS', REQUEST: 'GetFeatureInfo', VERSION: '1.3.0',
515
+ INFO_FORMAT: 'application/json', STYLES: '', FEATURE_COUNT: 1
516
+ }, fi.params || {});
517
+ const key = String(p.VERSION).indexOf('1.1') === 0 ? 'SRS' : 'CRS';
518
+ delete p.SRS; delete p.CRS;
519
+ p[key] = fi.projection || 'EPSG:3857';
520
+ p.LAYERS = fi.layers;
521
+ p.QUERY_LAYERS = fi.queryLayers || fi.layers;
522
+ 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
523
+ p.BBOX = [c[0] - d, c[1] - d, c[0] + d, c[1] + d].join(',');
524
+ return query(fi.url, p);
525
+ }
526
+
527
+ /**
528
+ * Band value in a GetFeatureInfo response.
529
+ *
530
+ * The band's property name is not standard - GeoServer calls it GRAY_INDEX for a
531
+ * single-band coverage, but a styled or renamed layer answers otherwise. Without an
532
+ * explicit `property` the first finite number wins, which is right whenever the coverage
533
+ * carries one band, and is why `property` exists for when it does not.
534
+ */
535
+ function bandValue(body, property) {
536
+ const f = body && body.features && body.features[0];
537
+ const props = f && f.properties;
538
+ if (!props) return null;
539
+ if (property) { const v = Number(props[property]); return isFinite(v) ? v : null; }
540
+ for (const k of Object.keys(props)) { const v = Number(props[k]); if (props[k] !== null && props[k] !== '' && isFinite(v)) return v; }
541
+ return null;
542
+ }
543
+
222
544
  /** Web Mercator pixel coordinates at zoom `z`, origin at the top-left corner of the world. */
223
545
  function worldPixel(lon, lat, z, tileSize) {
224
546
  const n = tileSize * Math.pow(2, z);
@@ -238,7 +560,9 @@ import * as d3 from 'd3';
238
560
  /** @param {Object} cfg `url`, `encoding`, `tileSize`, `concurrency`. */
239
561
  constructor(cfg) {
240
562
  this.cfg = cfg;
241
- this.decode = DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium;
563
+ this.decode = (typeof cfg.encoding === 'function') ? cfg.encoding
564
+ : (DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium);
565
+ this.tileUrl = tileUrlFn(cfg);
242
566
  this.tiles = new Map(); // "z/x/y" -> RGBA pixels, or null if the tile was lost
243
567
  }
244
568
 
@@ -270,7 +594,8 @@ import * as d3 from 'd3';
270
594
  const data = this.tiles.get(r.key);
271
595
  if (!data) return null;
272
596
  const o = ((r.jj % ts) * ts + (r.ii % ts)) * 4;
273
- return this.decode(data[o], data[o + 1], data[o + 2]);
597
+ const v = this.decode(data[o], data[o + 1], data[o + 2], data[o + 3]);
598
+ return (v == null || !isFinite(v)) ? null : v;
274
599
  }
275
600
 
276
601
  /**
@@ -304,7 +629,7 @@ import * as d3 from 'd3';
304
629
  /** Pixels of one tile, or null if it could not be read. */
305
630
  _fetch(key) {
306
631
  const parts = key.split('/');
307
- const url = this.cfg.url.replace('{z}', parts[0]).replace('{x}', parts[1]).replace('{y}', parts[2]);
632
+ const url = this.tileUrl(+parts[0], +parts[1], +parts[2]);
308
633
  return new Promise((resolve) => {
309
634
  const img = new Image();
310
635
  // Without this attribute the canvas is tainted and getImageData throws: the tile
@@ -346,13 +671,44 @@ import * as d3 from 'd3';
346
671
  }
347
672
  }
348
673
 
349
- /** The `dem` option (true | source name | object) → a full configuration, or null. */
674
+ /**
675
+ * The `dem` option (true | source name | sampling function | object) → a full
676
+ * configuration, or null.
677
+ *
678
+ * A `sample` function short-circuits the tile machinery entirely: the application
679
+ * answers with the elevations itself, from wherever it can reach them - a GeoServer
680
+ * WCS coverage, a GeoTIFF decoded with geotiff.js, a national elevation API. Only the
681
+ * transport is delegated; the control keeps the sequencing, the all-or-nothing rule,
682
+ * the spinner and the `demload` event, which is where the subtle parts live.
683
+ *
684
+ * That extension point rather than a WMS/WCS/GeoTIFF mode per protocol: reading a
685
+ * GeoTIFF means a full decoder, and this library has no runtime dependency to spend
686
+ * on one that most users would never load.
687
+ */
350
688
  function demConfig(opt) {
351
689
  if (!opt) return null;
690
+ if (typeof opt === 'function') return Object.assign({}, DEM_DEFAULTS, { sample: opt });
352
691
  const raw = (opt === true || typeof opt === 'string') ? { source: opt === true ? 'terrarium' : opt } : Object.assign({}, opt);
353
- const preset = DEM_PRESETS[raw.source] || (raw.url ? {} : DEM_PRESETS.terrarium);
692
+ if (typeof raw.sample === 'function') return Object.assign({}, DEM_DEFAULTS, raw);
693
+ // A point-query source: no tile grid, no pixel decoding.
694
+ if (raw.featureInfo) {
695
+ const fiCfg = Object.assign({}, DEM_DEFAULTS, raw);
696
+ fiCfg.sample = featureInfoSampler(fiCfg);
697
+ return fiCfg;
698
+ }
699
+ // An ol/source/DataTile (GeoTIFF above all) carries values, not URLs: its own path.
700
+ if (raw.olSource && typeof raw.olSource.getTileUrlFunction !== 'function' &&
701
+ typeof raw.olSource.getTile === 'function') {
702
+ const dtCfg = Object.assign({}, DEM_DEFAULTS, raw);
703
+ dtCfg.sample = dataTileSampler(dtCfg);
704
+ return dtCfg;
705
+ }
706
+ // Tiles: an OpenLayers source or a WMS both stand in for the url template.
707
+ const hasTiles = raw.url || raw.wms || raw.olSource;
708
+ const preset = DEM_PRESETS[raw.source] || (hasTiles ? {} : DEM_PRESETS.terrarium);
354
709
  const cfg = Object.assign({}, DEM_DEFAULTS, preset, raw);
355
- return cfg.url ? cfg : null;
710
+ if (cfg.api === 'ign') { cfg.sample = ignSampler(cfg); return cfg; } // a point API
711
+ return (cfg.url || cfg.wms || cfg.olSource) ? cfg : null;
356
712
  }
357
713
 
358
714
  /**
@@ -401,6 +757,7 @@ import * as d3 from 'd3';
401
757
  * @property {boolean} [responsive=true] Adapt width/placement; mobile included.
402
758
  * @property {number} [mobileBreakpoint=640] Below this width: mobile mode (100% width, top/bottom only).
403
759
  * @property {boolean} [zoom=false] A/B buttons to crop map + profile to a sub-range.
760
+ * @property {boolean} [exportPng=false] Toolbar button exporting the whole panel as a PNG.
404
761
  * @property {boolean} [ignoreStops=true] When computing time, ignore stopped segments (moving time).
405
762
  * @property {number} [stopSpeed=0.5] Speed threshold (m/s) below which a segment counts as a stop.
406
763
  * @property {Array<'distance'|'elevation'|'slope'|'time'>} [tooltipItems=['distance','elevation']] Tooltip content (`'time'` = elapsed time at the cursor, if the track has time data).
@@ -409,7 +766,16 @@ import * as d3 from 'd3';
409
766
  * @property {?string} [titleLink=null] Feature property holding a URL → clickable title.
410
767
  * @property {number} [maxPoints=2000] Decimation for render/interaction (stats use full data).
411
768
  * @property {?import('ol/proj/Projection').default|string} [dataProjection=null] Projection of the feature coordinates.
412
- * @property {?(boolean|string|Object)} [dem='terrarium'] Fill missing elevations from a terrain model. `'terrarium'` (default) or `true` = AWS Terrain Tiles (keyless); `null` disables it; or `{url,encoding:'terrarium'|'mapbox',zoom,maxZoom,maxTiles,tileSize,concurrency}`.
769
+ * @property {?(boolean|string|Function|Object)} [dem='terrarium'] Fill missing elevations
770
+ * from a terrain model. Sources: `'terrarium'` (default) or `true` = AWS Terrain Tiles;
771
+ * `'ign'` = IGN Géoplateforme RGE ALTI (France, keyless, `apiKey` optional);
772
+ * `{url}` = XYZ template; `{wms:{url,layers,params}}` = WMS tiles;
773
+ * `{olSource}` = any `ol/source/TileImage` (XYZ, TileWMS, …);
774
+ * `{featureInfo:{url,layers,property}}` = WMS GetFeatureInfo, one request per point,
775
+ * for a greyscale coverage that cannot be decoded from its pixels (slow);
776
+ * a function or `{sample}` `(lonlats, ctx) => number[]|Promise<number[]>` to source them
777
+ * yourself; `null` disables the whole thing.
778
+ * Decoding: `encoding` is `'terrarium'`, `'mapbox'`, or a function `(r,g,b,a) => metres`.
413
779
  */
414
780
 
415
781
  /**
@@ -490,6 +856,8 @@ import * as d3 from 'd3';
490
856
  this._btnA = mkBtn('oep-a', ICON_A, o.labels.zoomStart, () => this._arm('A'));
491
857
  this._btnB = mkBtn('oep-b', ICON_B, o.labels.zoomEnd, () => this._arm('B'));
492
858
  this._btnAll = mkBtn('oep-all', ICON_ALL, o.labels.zoomAll, () => this._exitZoom());
859
+ // Last of the toolbar, so it sits to the right of the zoom buttons.
860
+ this._btnPng = mkBtn('oep-png', ICON_PNG, o.labels.exportPng, () => this.exportPNG());
493
861
  header.appendChild(this._toolbar);
494
862
 
495
863
  const btn = document.createElement('button');
@@ -674,7 +1042,7 @@ import * as d3 from 'd3';
674
1042
  if (patch && (patch.theme || 'color' in patch)) this._applyTheme();
675
1043
  if (patch && ('transparency' in patch || 'transparencyLevel' in patch)) this._applyTransparency();
676
1044
  if (patch && 'collapsable' in patch) this._applyCollapsable();
677
- if (patch && 'zoom' in patch) this._updateZoomButtons();
1045
+ if (patch && ('zoom' in patch || 'exportPng' in patch)) this._updateZoomButtons();
678
1046
  if (patch && typeof patch.width !== 'undefined' && typeof patch.width === 'number') this.options.width = patch.width;
679
1047
  if (patch && 'dem' in patch) { this._demZ = null; this._demFor = null; }
680
1048
  if (this._feature) { this._compute(); this._fillFromDem(this._feature); this._updateZoomButtons(); if (this._collapsed) this._renderTitle(); else this._render(); }
@@ -702,7 +1070,9 @@ import * as d3 from 'd3';
702
1070
  const cfg = demConfig(this.options.dem);
703
1071
  if (!cfg || !feature || this._demFor === feature) return;
704
1072
  if (ElevationProfile.featureHasZ(feature)) return; // the track already carries its Z
705
- if (typeof Image === 'undefined' || typeof document === 'undefined') return;
1073
+ // Canvas decoding needs a browser; a `sample` function does not, and must stay
1074
+ // usable where there is no DOM.
1075
+ if (!cfg.sample && (typeof Image === 'undefined' || typeof document === 'undefined')) return;
706
1076
 
707
1077
  const geom = feature.getGeometry && feature.getGeometry();
708
1078
  if (!geom) return;
@@ -715,28 +1085,67 @@ import * as d3 from 'd3';
715
1085
  // Sequence number: a track clicked while another is loading must win, otherwise the
716
1086
  // slowest response would overwrite the profile on screen.
717
1087
  const seq = ++this._demSeq;
1088
+ this._demLoading = true;
1089
+
1090
+ // A misconfigured source must not take the profile down with it. _fillFromDem runs
1091
+ // inside setFeature, so anything thrown here would reach the caller and leave no
1092
+ // chart at all - where the whole point is that the fill is a supplement.
1093
+ try {
1094
+ this._startFill(cfg, seq, feature, lonlats, dataProj);
1095
+ } catch (e) {
1096
+ this._demDone(seq, feature, null, lonlats.length, null, 0);
1097
+ }
1098
+ }
1099
+
1100
+ /** @private */
1101
+ _startFill(cfg, seq, feature, lonlats, dataProj) {
1102
+ if (cfg.sample) {
1103
+ // Wrapped in a promise chain so a function that throws synchronously fails the
1104
+ // same way as one that rejects - a source that misbehaves must not leave the
1105
+ // spinner turning forever.
1106
+ Promise.resolve()
1107
+ .then(() => cfg.sample(lonlats, { feature, projection: dataProj }))
1108
+ .then((zs) => this._demDone(seq, feature, zs, lonlats.length, null, 0))
1109
+ .catch(() => this._demDone(seq, feature, null, lonlats.length, null, 0));
1110
+ return;
1111
+ }
1112
+
718
1113
  const sampler = new DemSampler(cfg);
719
1114
  const z = demZoomFor(sampler, lonlats, cfg);
720
- this._demLoading = true;
721
1115
  sampler.load(sampler.tilesFor(lonlats, z)).then((ok) => {
722
- // A newer fill has taken over: it owns _demLoading and will clear it itself.
723
- if (seq !== this._demSeq || this._feature !== feature) return;
724
1116
  const zs = ok ? lonlats.map((ll) => sampler.sample(ll[0], ll[1], z)) : null;
725
- const complete = !!zs && zs.every((v) => v != null && isFinite(v));
726
- this._demLoading = false;
727
- if (complete) { this._demZ = zs; this._demFor = feature; this._compute(); }
728
- // Redrawn even on failure: the spinner has to give way to the flat profile.
729
- this._updateZoomButtons();
730
- if (!this._collapsed) this._render();
731
- /**
732
- * Fired once a terrain-model fill has completed (or failed).
733
- * @event demload
734
- * @property {boolean} ok Whether every point could be sampled.
735
- * @property {number} zoom Tile zoom level used.
736
- * @property {number} tiles Tiles fetched.
737
- */
738
- this.dispatchEvent({ type: 'demload', ok: complete, zoom: z, tiles: sampler.tiles.size });
739
- });
1117
+ this._demDone(seq, feature, zs, lonlats.length, z, sampler.tiles.size);
1118
+ }).catch(() => this._demDone(seq, feature, null, lonlats.length, z, 0));
1119
+ }
1120
+
1121
+ /**
1122
+ * Outcome of a fill, whatever produced it: adopt the elevations, drop the spinner,
1123
+ * redraw, announce.
1124
+ *
1125
+ * A result of the wrong length is refused outright rather than padded. Elevations one
1126
+ * can no longer map to their points are worse than absent ones: they would land on the
1127
+ * wrong places, and nothing downstream would notice.
1128
+ *
1129
+ * @fires demload
1130
+ * @private
1131
+ */
1132
+ _demDone(seq, feature, zs, expected, zoom, tiles) {
1133
+ // A newer fill has taken over: it owns _demLoading and will clear it itself.
1134
+ if (seq !== this._demSeq || this._feature !== feature) return;
1135
+ const usable = Array.isArray(zs) && zs.length === expected && zs.every((v) => v != null && isFinite(v));
1136
+ this._demLoading = false;
1137
+ if (usable) { this._demZ = zs; this._demFor = feature; this._compute(); }
1138
+ // Redrawn even on failure: the spinner has to give way to the flat profile.
1139
+ this._updateZoomButtons();
1140
+ if (!this._collapsed) this._render();
1141
+ /**
1142
+ * Fired once a terrain-model fill has completed (or failed).
1143
+ * @event demload
1144
+ * @property {boolean} ok Whether every point could be sampled.
1145
+ * @property {?number} zoom Tile zoom level used, `null` for a custom sampler.
1146
+ * @property {number} tiles Tiles fetched, `0` for a custom sampler.
1147
+ */
1148
+ this.dispatchEvent({ type: 'demload', ok: usable, zoom, tiles });
740
1149
  }
741
1150
 
742
1151
  // ---------- computation -------------------------------------------
@@ -1050,11 +1459,147 @@ import * as d3 from 'd3';
1050
1459
  this._adjustAttribution();
1051
1460
  }
1052
1461
 
1462
+ // ---------- PNG export ---------------------------------------------
1463
+ /**
1464
+ * Properties frozen onto the exported clone.
1465
+ *
1466
+ * A serialized SVG carries no stylesheet: rules that live in the CSS file, and every
1467
+ * `var(--oep-*)` they resolve, vanish the moment the markup leaves the document. The
1468
+ * export would come out as black shapes on nothing. So the computed value of each
1469
+ * painting property is written inline, node by node.
1470
+ */
1471
+ static get _EXPORT_PROPS() {
1472
+ return ['fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-dasharray',
1473
+ 'stroke-linecap', 'stroke-linejoin', 'opacity', 'font-family', 'font-size',
1474
+ 'font-weight', 'text-anchor', 'shape-rendering'];
1475
+ }
1476
+
1477
+ /** Copies the computed painting styles of `src` onto `dst`, recursively. */
1478
+ _freezeStyles(src, dst) {
1479
+ const props = ElevationProfile._EXPORT_PROPS;
1480
+ const cs = getComputedStyle(src);
1481
+ let inline = '';
1482
+ for (const p of props) { const v = cs.getPropertyValue(p); if (v) inline += `${p}:${v};`; }
1483
+ dst.setAttribute('style', inline);
1484
+ const a = src.children, b = dst.children;
1485
+ for (let i = 0; i < a.length && i < b.length; i++) this._freezeStyles(a[i], b[i]);
1486
+ }
1487
+
1488
+ /**
1489
+ * The whole panel as an SVG string: background, title, stats, legend, chart.
1490
+ *
1491
+ * Rebuilt rather than screenshotted. The header is HTML and the chart is SVG, and the
1492
+ * only way to put HTML in an SVG is a `foreignObject`, which browsers refuse to
1493
+ * rasterise consistently. Redrawing the two text lines as `<text>` is a handful of
1494
+ * lines and works everywhere.
1495
+ *
1496
+ * The current-position indicator is dropped: it marks where the pointer happens to be,
1497
+ * which means nothing once the image is saved.
1498
+ */
1499
+ _exportSvg() {
1500
+ const chart = this._body.querySelector('svg');
1501
+ if (!chart) return null;
1502
+ const cs = getComputedStyle(this.element);
1503
+ const bg = cs.getPropertyValue('--oep-bg').trim() || '#fff';
1504
+ const fg = cs.getPropertyValue('--oep-text').trim() || '#222';
1505
+ const font = cs.fontFamily || 'system-ui, sans-serif';
1506
+ const W = +chart.getAttribute('width'), H = +chart.getAttribute('height');
1507
+ const pad = 8, titleH = 20, statsH = this._statsEl.textContent ? 15 : 0;
1508
+ const legend = (this._legendEl.style.display !== 'none') ? this._legendEl : null;
1509
+ const legH = legend ? 18 : 0;
1510
+ const top = pad + titleH + statsH + legH;
1511
+
1512
+ const clone = chart.cloneNode(true);
1513
+ // The pointer indicator and the hit-test overlay have no place in a saved image.
1514
+ clone.querySelectorAll('.oep-focus, .oep-overlay').forEach((n) => n.remove());
1515
+ this._freezeStyles(chart, clone);
1516
+ // width/height are kept: a nested <svg> without them fills the parent viewport, so
1517
+ // the chart would be stretched over the header's height as well.
1518
+
1519
+ const esc2 = (t) => esc(String(t));
1520
+ const parts = [];
1521
+ parts.push(`<rect width="${W + 2 * pad}" height="${H + top + pad}" fill="${esc2(bg)}"/>`);
1522
+ 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>`);
1523
+ 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>`);
1524
+ if (legend) {
1525
+ let x = pad;
1526
+ const y = pad + titleH + statsH + 12;
1527
+ for (const item of legend.querySelectorAll('.oep-leg-it')) {
1528
+ const sw = item.querySelector('.oep-sw');
1529
+ const color = sw ? getComputedStyle(sw).backgroundColor : 'none';
1530
+ const label = item.textContent.trim();
1531
+ parts.push(`<rect x="${x}" y="${y - 8}" width="10" height="10" fill="${esc2(color)}"/>`);
1532
+ parts.push(`<text x="${x + 14}" y="${y}" style="font-family:${esc2(font)};font-size:10px;fill:${esc2(fg)}">${esc2(label)}</text>`);
1533
+ x += 14 + label.length * 5.6 + 10;
1534
+ }
1535
+ }
1536
+ parts.push(`<g transform="translate(${pad},${top})">${new XMLSerializer().serializeToString(clone)}</g>`);
1537
+ return {
1538
+ width: W + 2 * pad, height: H + top + pad,
1539
+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${W + 2 * pad}" height="${H + top + pad}" ` +
1540
+ `viewBox="0 0 ${W + 2 * pad} ${H + top + pad}">${parts.join('')}</svg>`
1541
+ };
1542
+ }
1543
+
1544
+ /**
1545
+ * Export the whole panel - title, stats, legend and chart - as a PNG.
1546
+ *
1547
+ * Resolves with the Blob. Unless `download` is false, it also saves the file, which is
1548
+ * what the toolbar button does.
1549
+ *
1550
+ * @param {{scale?:number, filename?:string, download?:boolean}} [opts]
1551
+ * `scale` defaults to the device pixel ratio, so the image is not soft on a retina
1552
+ * screen. `filename` defaults to the track title.
1553
+ * @returns {Promise<Blob>}
1554
+ */
1555
+ exportPNG(opts) {
1556
+ const o = opts || {};
1557
+ const built = this._exportSvg();
1558
+ if (!built) return Promise.reject(new Error('ol-elevation-profile: nothing to export'));
1559
+ const scale = o.scale || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
1560
+ return new Promise((resolve, reject) => {
1561
+ const img = new Image();
1562
+ img.onload = () => {
1563
+ try {
1564
+ const cv = document.createElement('canvas');
1565
+ cv.width = Math.round(built.width * scale);
1566
+ cv.height = Math.round(built.height * scale);
1567
+ const ctx = cv.getContext('2d');
1568
+ ctx.scale(scale, scale);
1569
+ ctx.drawImage(img, 0, 0);
1570
+ cv.toBlob((blob) => {
1571
+ if (!blob) { reject(new Error('ol-elevation-profile: PNG encoding failed')); return; }
1572
+ if (o.download !== false) this._save(blob, o.filename);
1573
+ resolve(blob);
1574
+ }, 'image/png');
1575
+ } catch (e) { reject(e); }
1576
+ };
1577
+ img.onerror = () => reject(new Error('ol-elevation-profile: SVG could not be rasterised'));
1578
+ // Encoded as a data URL rather than a blob: URL - a blob: source taints the canvas
1579
+ // in some browsers, and toBlob would then throw a security error.
1580
+ img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(built.svg);
1581
+ });
1582
+ }
1583
+
1584
+ /** @private */
1585
+ _save(blob, filename) {
1586
+ const name = filename || `${(this._titleEl.textContent || 'profile').replace(/[\\/:*?"<>|]+/g, '-').trim()}.png`;
1587
+ const url = URL.createObjectURL(blob);
1588
+ const a = document.createElement('a');
1589
+ a.href = url; a.download = name;
1590
+ document.body.appendChild(a); a.click(); a.remove();
1591
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1592
+ }
1593
+
1053
1594
  // ---------- zoom A/B ----------------------------------------------
1054
1595
  _arm(which) { this._armed = (this._armed === which) ? null : which; this._updateZoomButtons(); if (this._focus) this._render(); }
1055
1596
  _updateZoomButtons() {
1056
- const show = !!this.options.zoom && !!this._feature;
1057
- this._toolbar.style.display = show ? '' : 'none';
1597
+ const o = this.options, has = !!this._feature;
1598
+ const show = !!o.zoom && has;
1599
+ const png = !!o.exportPng && has;
1600
+ // The toolbar carries both: it stays visible as long as either has something to show.
1601
+ this._toolbar.style.display = (show || png) ? '' : 'none';
1602
+ this._btnPng.style.display = png ? '' : 'none';
1058
1603
  const crop = this._cropMode;
1059
1604
  this._btnA.style.display = show && !crop ? '' : 'none';
1060
1605
  this._btnB.style.display = show && !crop ? '' : 'none';