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.
@@ -17,7 +17,8 @@
17
17
  import Control from 'ol/control/Control.js';
18
18
  import Overlay from 'ol/Overlay.js';
19
19
  import { unByKey } from 'ol/Observable.js';
20
- 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';
21
22
  import { getDistance } from 'ol/sphere.js';
22
23
  import { boundingExtent } from 'ol/extent.js';
23
24
  import * as d3 from 'd3';
@@ -67,6 +68,7 @@ import * as d3 from 'd3';
67
68
  responsive: true, // adapts width/placement, mobile included
68
69
  mobileBreakpoint: 640, // <= screen width -> mobile mode (100% width, top/bottom)
69
70
  zoom: false, // start/end buttons cropping map + profile to A..B
71
+ exportPng: false, // toolbar button exporting the panel as a PNG
70
72
  ignoreStops: true, // duration = moving time (stops excluded)
71
73
  stopSpeed: 0.5, // stop threshold in m/s (~1.8 km/h)
72
74
  tooltipItems: ['distance', 'elevation'],
@@ -79,6 +81,7 @@ import * as d3 from 'd3';
79
81
  time: 'Temps', duration: 'Durée',
80
82
  durationUnits: { s: 'sec', m: 'min', h: 'h', d: 'j' },
81
83
  zoomStart: 'Définir le début (A)', zoomEnd: 'Définir la fin (B)', zoomAll: 'Tout voir',
84
+ exportPng: 'Exporter en PNG',
82
85
  loading: 'Chargement du profil altimétrique'
83
86
  }
84
87
  };
@@ -184,6 +187,7 @@ import * as d3 from 'd3';
184
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>';
185
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>';
186
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>';
187
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>';
188
192
 
189
193
  // ----- digital elevation model (DEM) -----------------------------------
@@ -206,17 +210,335 @@ import * as d3 from 'd3';
206
210
  encoding: 'terrarium',
207
211
  maxZoom: 14,
208
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)'
209
236
  }
210
237
  };
211
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
+
212
293
  const DEM_DEFAULTS = { source: 'terrarium', zoom: 'auto', maxZoom: 14, maxTiles: 32, concurrency: 6, tileSize: 256 };
213
294
 
214
- /** RGB → metres decoders, one per encoding convention. */
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
+ */
215
307
  const DEM_DECODERS = {
216
308
  terrarium: (r, g, b) => (r * 256 + g + b / 256) - 32768,
217
309
  mapbox: (r, g, b) => -10000 + (r * 65536 + g * 256 + b) * 0.1
218
310
  };
219
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
+
220
542
  /** Web Mercator pixel coordinates at zoom `z`, origin at the top-left corner of the world. */
221
543
  function worldPixel(lon, lat, z, tileSize) {
222
544
  const n = tileSize * Math.pow(2, z);
@@ -236,7 +558,9 @@ import * as d3 from 'd3';
236
558
  /** @param {Object} cfg `url`, `encoding`, `tileSize`, `concurrency`. */
237
559
  constructor(cfg) {
238
560
  this.cfg = cfg;
239
- this.decode = DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium;
561
+ this.decode = (typeof cfg.encoding === 'function') ? cfg.encoding
562
+ : (DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium);
563
+ this.tileUrl = tileUrlFn(cfg);
240
564
  this.tiles = new Map(); // "z/x/y" -> RGBA pixels, or null if the tile was lost
241
565
  }
242
566
 
@@ -268,7 +592,8 @@ import * as d3 from 'd3';
268
592
  const data = this.tiles.get(r.key);
269
593
  if (!data) return null;
270
594
  const o = ((r.jj % ts) * ts + (r.ii % ts)) * 4;
271
- return this.decode(data[o], data[o + 1], data[o + 2]);
595
+ const v = this.decode(data[o], data[o + 1], data[o + 2], data[o + 3]);
596
+ return (v == null || !isFinite(v)) ? null : v;
272
597
  }
273
598
 
274
599
  /**
@@ -302,7 +627,7 @@ import * as d3 from 'd3';
302
627
  /** Pixels of one tile, or null if it could not be read. */
303
628
  _fetch(key) {
304
629
  const parts = key.split('/');
305
- const url = this.cfg.url.replace('{z}', parts[0]).replace('{x}', parts[1]).replace('{y}', parts[2]);
630
+ const url = this.tileUrl(+parts[0], +parts[1], +parts[2]);
306
631
  return new Promise((resolve) => {
307
632
  const img = new Image();
308
633
  // Without this attribute the canvas is tainted and getImageData throws: the tile
@@ -344,13 +669,44 @@ import * as d3 from 'd3';
344
669
  }
345
670
  }
346
671
 
347
- /** The `dem` option (true | source name | object) → a full configuration, or null. */
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
+ */
348
686
  function demConfig(opt) {
349
687
  if (!opt) return null;
688
+ if (typeof opt === 'function') return Object.assign({}, DEM_DEFAULTS, { sample: opt });
350
689
  const raw = (opt === true || typeof opt === 'string') ? { source: opt === true ? 'terrarium' : opt } : Object.assign({}, opt);
351
- const preset = DEM_PRESETS[raw.source] || (raw.url ? {} : DEM_PRESETS.terrarium);
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);
352
707
  const cfg = Object.assign({}, DEM_DEFAULTS, preset, raw);
353
- return cfg.url ? cfg : null;
708
+ if (cfg.api === 'ign') { cfg.sample = ignSampler(cfg); return cfg; } // a point API
709
+ return (cfg.url || cfg.wms || cfg.olSource) ? cfg : null;
354
710
  }
355
711
 
356
712
  /**
@@ -399,6 +755,7 @@ import * as d3 from 'd3';
399
755
  * @property {boolean} [responsive=true] Adapt width/placement; mobile included.
400
756
  * @property {number} [mobileBreakpoint=640] Below this width: mobile mode (100% width, top/bottom only).
401
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.
402
759
  * @property {boolean} [ignoreStops=true] When computing time, ignore stopped segments (moving time).
403
760
  * @property {number} [stopSpeed=0.5] Speed threshold (m/s) below which a segment counts as a stop.
404
761
  * @property {Array<'distance'|'elevation'|'slope'|'time'>} [tooltipItems=['distance','elevation']] Tooltip content (`'time'` = elapsed time at the cursor, if the track has time data).
@@ -407,7 +764,16 @@ import * as d3 from 'd3';
407
764
  * @property {?string} [titleLink=null] Feature property holding a URL → clickable title.
408
765
  * @property {number} [maxPoints=2000] Decimation for render/interaction (stats use full data).
409
766
  * @property {?import('ol/proj/Projection').default|string} [dataProjection=null] Projection of the feature coordinates.
410
- * @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}`.
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`.
411
777
  */
412
778
 
413
779
  /**
@@ -488,6 +854,8 @@ import * as d3 from 'd3';
488
854
  this._btnA = mkBtn('oep-a', ICON_A, o.labels.zoomStart, () => this._arm('A'));
489
855
  this._btnB = mkBtn('oep-b', ICON_B, o.labels.zoomEnd, () => this._arm('B'));
490
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());
491
859
  header.appendChild(this._toolbar);
492
860
 
493
861
  const btn = document.createElement('button');
@@ -672,7 +1040,7 @@ import * as d3 from 'd3';
672
1040
  if (patch && (patch.theme || 'color' in patch)) this._applyTheme();
673
1041
  if (patch && ('transparency' in patch || 'transparencyLevel' in patch)) this._applyTransparency();
674
1042
  if (patch && 'collapsable' in patch) this._applyCollapsable();
675
- if (patch && 'zoom' in patch) this._updateZoomButtons();
1043
+ if (patch && ('zoom' in patch || 'exportPng' in patch)) this._updateZoomButtons();
676
1044
  if (patch && typeof patch.width !== 'undefined' && typeof patch.width === 'number') this.options.width = patch.width;
677
1045
  if (patch && 'dem' in patch) { this._demZ = null; this._demFor = null; }
678
1046
  if (this._feature) { this._compute(); this._fillFromDem(this._feature); this._updateZoomButtons(); if (this._collapsed) this._renderTitle(); else this._render(); }
@@ -700,7 +1068,9 @@ import * as d3 from 'd3';
700
1068
  const cfg = demConfig(this.options.dem);
701
1069
  if (!cfg || !feature || this._demFor === feature) return;
702
1070
  if (ElevationProfile.featureHasZ(feature)) return; // the track already carries its Z
703
- if (typeof Image === 'undefined' || typeof document === 'undefined') return;
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;
704
1074
 
705
1075
  const geom = feature.getGeometry && feature.getGeometry();
706
1076
  if (!geom) return;
@@ -713,28 +1083,67 @@ import * as d3 from 'd3';
713
1083
  // Sequence number: a track clicked while another is loading must win, otherwise the
714
1084
  // slowest response would overwrite the profile on screen.
715
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
+
716
1111
  const sampler = new DemSampler(cfg);
717
1112
  const z = demZoomFor(sampler, lonlats, cfg);
718
- this._demLoading = true;
719
1113
  sampler.load(sampler.tilesFor(lonlats, z)).then((ok) => {
720
- // A newer fill has taken over: it owns _demLoading and will clear it itself.
721
- if (seq !== this._demSeq || this._feature !== feature) return;
722
1114
  const zs = ok ? lonlats.map((ll) => sampler.sample(ll[0], ll[1], z)) : null;
723
- const complete = !!zs && zs.every((v) => v != null && isFinite(v));
724
- this._demLoading = false;
725
- if (complete) { this._demZ = zs; this._demFor = feature; this._compute(); }
726
- // Redrawn even on failure: the spinner has to give way to the flat profile.
727
- this._updateZoomButtons();
728
- if (!this._collapsed) this._render();
729
- /**
730
- * Fired once a terrain-model fill has completed (or failed).
731
- * @event demload
732
- * @property {boolean} ok Whether every point could be sampled.
733
- * @property {number} zoom Tile zoom level used.
734
- * @property {number} tiles Tiles fetched.
735
- */
736
- this.dispatchEvent({ type: 'demload', ok: complete, zoom: z, tiles: sampler.tiles.size });
737
- });
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 });
738
1147
  }
739
1148
 
740
1149
  // ---------- computation -------------------------------------------
@@ -1048,11 +1457,147 @@ import * as d3 from 'd3';
1048
1457
  this._adjustAttribution();
1049
1458
  }
1050
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
+
1051
1592
  // ---------- zoom A/B ----------------------------------------------
1052
1593
  _arm(which) { this._armed = (this._armed === which) ? null : which; this._updateZoomButtons(); if (this._focus) this._render(); }
1053
1594
  _updateZoomButtons() {
1054
- const show = !!this.options.zoom && !!this._feature;
1055
- this._toolbar.style.display = show ? '' : 'none';
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';
1056
1601
  const crop = this._cropMode;
1057
1602
  this._btnA.style.display = show && !crop ? '' : 'none';
1058
1603
  this._btnB.style.display = show && !crop ? '' : 'none';