@raruto/leaflet-elevation 2.6.0 → 2.7.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.
@@ -1,1709 +1,1379 @@
1
- (function (factory) {
2
- typeof define === 'function' && define.amd ? define(factory) :
3
- factory();
4
- })((function () { 'use strict';
5
-
6
- /**
7
- * TODO: exget computed styles of theese values from actual "CSS vars"
8
- **/
9
- const Colors = {
10
- 'lightblue': { area: '#3366CC', alpha: 0.45, stroke: '#3366CC' },
11
- 'magenta' : { area: '#FF005E' },
12
- 'yellow' : { area: '#FF0' },
13
- 'purple' : { area: '#732C7B' },
14
- 'steelblue': { area: '#4682B4' },
15
- 'red' : { area: '#F00' },
16
- 'lime' : { area: '#9CC222', line: '#566B13' }
17
- };
18
-
19
- const SEC = 1000;
20
- const MIN = SEC * 60;
21
- const HOUR = MIN * 60;
22
- const DAY = HOUR * 24;
23
-
24
- function resolveURL(src, baseUrl) {
25
- return (new URL(src, (src.startsWith('../') || src.startsWith('./')) ? baseUrl : undefined)).toString()
26
- }
27
- /**
28
- * Convert a time (millis) to a human readable duration string (%Dd %H:%M'%S")
29
- */
30
- function formatTime(t) {
31
- let d = Math.floor(t / DAY);
32
- let h = Math.floor( (t - d * DAY) / HOUR);
33
- let m = Math.floor( (t - d * DAY - h * HOUR) / MIN);
34
- let s = Math.round( (t - d * DAY - h * HOUR - m * MIN) / SEC);
35
- if ( s === 60 ) { m++; s = 0; }
36
- if ( m === 60 ) { h++; m = 0; }
37
- if ( h === 24 ) { d++; h = 0; }
38
- return (d ? d + "d " : '') + h.toString().padStart(2, 0) + ':' + m.toString().padStart(2, 0) + "'" + s.toString().padStart(2, 0) + '"';
39
- }
40
-
41
- /**
42
- * Convert a time (millis) to human readable date string (dd-mm-yyyy hh:mm:ss)
43
- */
44
- function formatDate(format) {
45
- if (!format) {
46
- return (time) => (new Date(time)).toLocaleString().replaceAll('/', '-').replaceAll(',', ' ');
47
- } else if (format == 'time') {
48
- return (time) => (new Date(time)).toLocaleTimeString();
49
- } else if (format == 'date') {
50
- return (time) => (new Date(time)).toLocaleDateString();
51
- }
52
- return (time) => format(time);
53
- }
54
-
55
- /**
56
- * Generate download data event.
57
- */
58
- function saveFile(dataURI, fileName) {
59
- let a = create('a', '', { href: dataURI, target: '_new', download: fileName || "", style: "display:none;" });
60
- let b = document.body;
61
- b.appendChild(a);
62
- a.click();
63
- b.removeChild(a);
64
- }
65
-
66
-
67
- /**
68
- * Convert SVG Path into Path2D and then update canvas
69
- */
70
- function drawCanvas(ctx, path) {
71
- path.classed('canvas-path', true);
72
-
73
- ctx.beginPath();
74
- ctx.moveTo(0, 0);
75
- let p = new Path2D(path.attr('d'));
76
-
77
- ctx.strokeStyle = path.__strokeStyle || path.attr('stroke');
78
- ctx.fillStyle = path.__fillStyle || path.attr('fill');
79
- ctx.lineWidth = 1.25;
80
- ctx.globalCompositeOperation = 'source-over';
81
-
82
- // stroke opacity
83
- ctx.globalAlpha = path.attr('stroke-opacity') || 0.3;
84
- ctx.stroke(p);
85
-
86
- // fill opacity
87
- ctx.globalAlpha = path.attr('fill-opacity') || 0.45;
88
- ctx.fill(p);
89
-
90
- ctx.globalAlpha = 1;
91
-
92
- ctx.closePath();
93
- }
94
-
95
- /**
96
- * Loop and extract GPX Extensions handled by "@tmcw/toGeoJSON" (eg. "coordinateProperties" > "times")
97
- */
98
- function coordPropsToMeta(coordProps, name, parser) {
99
- return coordProps && (({props, point, id, isMulti }) => {
100
- if (props) {
101
- for (const key of coordProps) {
102
- if (key in props) {
103
- point.meta[name] = (parser || parseNumeric).call(this, (isMulti ? props[key][isMulti] : props[key]), id);
104
- break;
105
- }
106
- }
107
- }
108
- });
109
- }
110
-
111
- /**
112
- * Extract numeric property (id) from GeoJSON object
113
- */
114
- const parseNumeric = (property, id) => parseInt((typeof property === 'object' ? property[id] : property));
115
-
116
- /**
117
- * Extract datetime property (id) from GeoJSON object
118
- */
119
- const parseDate = (property, id) => new Date(Date.parse((typeof property === 'object' ? property[id] : property)));
120
-
121
- /**
122
- * A little bit shorter than L.DomUtil
123
- */
124
- const addClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.addClass(n, s));
125
- const removeClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.removeClass(n, s));
126
- const toggleClass = (n, str, cond) => (cond ? addClass : removeClass)(n, str);
127
- const replaceClass = (n, rem, add) => (rem && removeClass(n, rem)) || (add && addClass(n, add));
128
- const style = (n, k, v) => (typeof v === "undefined" && L.DomUtil.getStyle(n, k)) || n.style.setProperty(k, v);
129
- const toggleStyle = (n, k, v, cond) => style(n, k, cond ? v : '');
130
- const setAttributes = (n, attrs) => { for (let k in attrs) { n.setAttribute(k, attrs[k]); } };
131
- const toggleEvent = (el, e, fn, cond) => el[cond ? 'on' : 'off'](e, fn);
132
- const create = (tag, str, attrs, n) => { let elem = L.DomUtil.create(tag, str || ""); if (attrs) setAttributes(elem, attrs); if (n) append(n, elem); return elem; };
133
- const append = (n, c) => n.appendChild(c);
134
- const insert = (n, c, pos) => n.insertAdjacentElement(pos, c);
135
- const select = (str, n) => (n || document).querySelector(str);
136
- const each = (obj, fn) => { for (let i in obj) fn(obj[i], i); };
137
- const randomId = () => Math.random().toString(36).substr(2, 9);
138
-
139
- /**
140
- * TODO: use generators instead? (ie. "yield")
141
- */
142
- const iMax = (iVal, max = -Infinity) => (iVal > max ? iVal : max);
143
- const iMin = (iVal, min = +Infinity) => (iVal < min ? iVal : min);
144
- const iAvg = (iVal, avg = 0, idx = 1) => (iVal + avg * (idx - 1)) / idx;
145
- const iSum = (iVal, sum = 0) => iVal + sum;
146
-
147
- /**
148
- * Alias for some leaflet core functions
149
- */
150
- const { on, off } = L.DomEvent;
151
- const { throttle, wrapNum } = L.Util;
152
- const { hasClass } = L.DomUtil;
153
-
154
- /**
155
- * Limit floating point precision
156
- */
157
- const round = L.Util.formatNum;
158
-
159
- /**
160
- * Limit a number between min / max values
161
- */
162
- const clamp = (val, range) => range ? (val < range[0] ? range[0] : val > range[1] ? range[1] : val) : val;
163
-
164
- /**
165
- * Limit a delta difference between two values
166
- */
167
- const wrapDelta = (curr, prev, deltaMax) => Math.abs(curr - prev) > deltaMax ? prev + deltaMax * Math.sign(curr - prev) : curr;
168
-
169
- /**
170
- * A deep copy implementation that takes care of correct prototype chain and cycles, references
171
- *
172
- * @see https://web.dev/structured-clone/#features-and-limitations
173
- */
174
- function cloneDeep(o, skipProps = [], cache = []) {
175
- switch(!o || typeof o) {
176
- case 'object':
177
- const hit = cache.filter(c => o === c.original)[0];
178
- if (hit) return hit.copy; // handle circular structures
179
- const copy = Array.isArray(o) ? [] : Object.create(Object.getPrototypeOf(o));
180
- cache.push({ original: o, copy });
181
- Object
182
- .getOwnPropertyNames(o)
183
- .forEach(function (prop) {
184
- const propdesc = Object.getOwnPropertyDescriptor(o, prop);
185
- Object.defineProperty(
186
- copy,
187
- prop,
188
- propdesc.get || propdesc.set
189
- ? propdesc // just copy accessor properties
190
- : { // deep copy data properties
191
- writable: propdesc.writable,
192
- configurable: propdesc.configurable,
193
- enumerable: propdesc.enumerable,
194
- value: skipProps.includes(prop) ? propdesc.value : cloneDeep(propdesc.value, skipProps, cache),
195
- }
196
- );
197
- });
198
- return copy;
199
- case 'function':
200
- case 'symbol':
201
- console.warn('cloneDeep: ' + typeof o + 's not fully supported:', o);
202
- case true:
203
- // null, undefined or falsy primitive
204
- default:
205
- return o;
206
- }
207
- }
208
-
209
- var _ = {
210
- __proto__: null,
211
- Colors: Colors,
212
- addClass: addClass,
213
- append: append,
214
- clamp: clamp,
215
- cloneDeep: cloneDeep,
216
- coordPropsToMeta: coordPropsToMeta,
217
- create: create,
218
- drawCanvas: drawCanvas,
219
- each: each,
220
- formatDate: formatDate,
221
- formatTime: formatTime,
222
- hasClass: hasClass,
223
- iAvg: iAvg,
224
- iMax: iMax,
225
- iMin: iMin,
226
- iSum: iSum,
227
- insert: insert,
228
- off: off,
229
- on: on,
230
- parseDate: parseDate,
231
- parseNumeric: parseNumeric,
232
- randomId: randomId,
233
- removeClass: removeClass,
234
- replaceClass: replaceClass,
235
- resolveURL: resolveURL,
236
- round: round,
237
- saveFile: saveFile,
238
- select: select,
239
- setAttributes: setAttributes,
240
- style: style,
241
- throttle: throttle,
242
- toggleClass: toggleClass,
243
- toggleEvent: toggleEvent,
244
- toggleStyle: toggleStyle,
245
- wrapDelta: wrapDelta,
246
- wrapNum: wrapNum
247
- };
248
-
249
- var Options = {
250
- autofitBounds: true,
251
- autohide: false,
252
- autohideMarker: true,
253
- almostover: true,
254
- altitude: true,
255
- closeBtn: true,
256
- collapsed: false,
257
- detached: true,
258
- distance: true,
259
- distanceMarkers: { lazy: true, distance: true, direction: true },
260
- dragging: !L.Browser.mobile,
261
- downloadLink: 'link',
262
- elevationDiv: "#elevation-div",
263
- edgeScale: { bar: true, icon: false, coords: false },
264
- followMarker: true,
265
- imperial: false,
266
- legend: true,
267
- handlers: ["Distance", "Time", "Altitude", "Slope", "Speed", "Acceleration"],
268
- hotline: 'elevation',
269
- marker: 'elevation-line',
270
- markerIcon: L.divIcon({
271
- className: 'elevation-position-marker',
272
- html: '<i class="elevation-position-icon"></i>',
273
- iconSize: [32, 32],
274
- iconAnchor: [16, 16],
275
- }),
276
- position: "topright",
277
- polyline: {
278
- className: 'elevation-polyline',
279
- color: '#000',
280
- opacity: 0.75,
281
- weight: 5,
282
- lineCap: 'round'
283
- },
284
- polylineSegments: {
285
- className: 'elevation-polyline-segments',
286
- color: '#F00',
287
- interactive: false,
288
- },
289
- preferCanvas: false,
290
- reverseCoords: false,
291
- ruler: true,
292
- theme: "lightblue-theme",
293
- summary: 'inline',
294
- slope: false,
295
- speed: false,
296
- time: true,
297
- timeFactor: 3600,
298
- timestamps: false,
299
- trkStart: { className: 'start-marker', radius: 6, weight: 2, color: '#fff', fillColor: '#00d800', fillOpacity: 1, interactive: false },
300
- trkEnd: { className: 'end-marker', radius: 6, weight: 2, color: '#fff', fillColor: '#ff0606', fillOpacity: 1, interactive: false },
301
- waypoints: true,
302
- wptIcons: {
303
- '': L.divIcon({
304
- className: 'elevation-waypoint-marker',
305
- html: '<i class="elevation-waypoint-icon default"></i>',
306
- iconSize: [30, 30],
307
- iconAnchor: [8, 30],
308
- }),
309
- },
310
- wptLabels: true,
311
- xAttr: "dist",
312
- xLabel: "km",
313
- yAttr: "z",
314
- yLabel: "m",
315
- zFollow: false,
316
- zooming: !L.Browser.Mobile,
317
-
318
- // Quite uncommon and undocumented options
319
- margins: { top: 30, right: 30, bottom: 30, left: 40 },
320
- height: (screen.height * 0.3) || 200,
321
- width: (screen.width * 0.6) || 600,
322
- xTicks: undefined,
323
- yTicks: undefined,
324
-
325
- decimalsX: 2,
326
- decimalsY: 0,
327
- forceAxisBounds: false,
328
- interpolation: "curveLinear",
329
- yAxisMax: undefined,
330
- yAxisMin: undefined,
331
-
332
- // Prevent CORS issues for relative locations (dynamic import)
333
- srcFolder: ((document.currentScript && document.currentScript.src) || (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('leaflet-elevation.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('leaflet-elevation.js', document.baseURI).href)))).split("/").slice(0,-1).join("/") + '/',
334
- };
335
-
336
- // "leaflet-i18n" fallback
337
- if (!L._ || !L.i18n) {
338
- L._ = L.i18n = (string, data) => string;
339
- }
340
-
341
- const Elevation = L.Control.Elevation = L.Control.extend({
342
-
343
- includes: L.Evented ? L.Evented.prototype : L.Mixin.Events,
344
-
345
- options: Options,
346
- __mileFactor: 0.621371, // 1 km = (0.621371 mi)
347
- __footFactor: 3.28084, // 1 m = (3.28084 ft)
348
- __D3: 'https://unpkg.com/d3@7.8.4/dist/d3.min.js',
349
- __TOGEOJSON: 'https://unpkg.com/@tmcw/togeojson@5.6.2/dist/togeojson.umd.js',
350
- __LGEOMUTIL: 'https://unpkg.com/leaflet-geometryutil@0.10.1/src/leaflet.geometryutil.js',
351
- __LALMOSTOVER: 'https://unpkg.com/leaflet-almostover@1.0.1/src/leaflet.almostover.js',
352
- __LHOTLINE: '../libs/leaflet-hotline.min.js',
353
- __LDISTANCEM: '../libs/leaflet-distance-marker.min.js',
354
- __LEDGESCALE: '../libs/leaflet-edgescale.min.js',
355
- __LCHART: '../src/components/chart.js',
356
- __LMARKER: '../src/components/marker.js',
357
- __LSUMMARY: '../src/components/summary.js',
358
- __modulesFolder: '../src/handlers/',
359
- __btnIcon: '../images/elevation.svg',
360
-
361
- /*
362
- * Add data to the diagram either from GPX or GeoJSON and update the axis domain and data
363
- */
364
- addData(d, layer) {
365
- this.import(this.__D3)
366
- .then(() => {
367
- if (this._modulesLoaded) {
368
- layer = layer ?? (d.on && d);
369
- this._addData(d);
370
- this._addLayer(layer);
371
- this._fireEvt("eledata_added", { data: d, layer: layer, track_info: this.track_info });
372
- } else {
373
- this.once('modules_loaded', () => this.addData(d,layer));
374
- }
375
- });
376
- },
377
-
378
- /**
379
- * Adds the control to the given map.
380
- */
381
- addTo(map) {
382
- if (this.options.detached) {
383
- let parent = select(this.options.elevationDiv);
384
- let eleDiv = this.onAdd(map);
385
- parent ? append(parent, eleDiv) : insert(map.getContainer(), eleDiv, 'afterend');
386
- } else {
387
- L.Control.prototype.addTo.call(this, map);
388
- }
389
- return this;
390
- },
391
-
392
- /*
393
- * Reset data and display
394
- */
395
- clear() {
396
- if (this._marker) this._marker.remove();
397
- if (this._chart) this._clearChart();
398
- if (this._layers) this._clearLayers(this._layers);
399
- if (this._markers) this._clearLayers(this._markers);
400
- if (this._circleMarkers) this._circleMarkers.remove();
401
- if (this._hotline) this._hotline.eachLayer(l => l.options.renderer.remove()); // hotfix for: https://github.com/Raruto/leaflet-elevation/issues/233
402
- if (this._hotline) this._clearLayers(this._hotline);
403
-
404
- this._data = [];
405
- this.track_info = {};
406
-
407
- this._fireEvt("eledata_clear");
408
-
409
- this._updateChart();
410
- },
411
-
412
- _clearChart() {
413
- if (this._events && this._events.elechart_updated) {
414
- this._events.elechart_updated.forEach(({fn, ctx}) => this.off('elechart_updated', fn, ctx));
415
- }
416
- if (this._chart && this._chart._container) {
417
- this._chart._container.selectAll('g.point .point').remove();
418
- this._chart.clear();
419
- }
420
- },
421
-
422
- _clearLayers(l) {
423
- l = l || this._layers;
424
- if (l && l.eachLayer) {
425
- l.eachLayer(f => f.remove());
426
- l.clearLayers();
427
- }
428
- },
429
-
430
- /**
431
- * TODO: Create a base class to handle custom data attributes (heart rate, cadence, temperature, ...)
432
- *
433
- * @link https://leafletjs.com/examples/extending/extending-3-controls.html#handlers
434
- */
435
- // addHandler: function (name, HandlerClass) {
436
- // if (HandlerClass) {
437
- // let handler = this[name] = new HandlerClass(this);
438
- // this.handlers.push(handler);
439
- // if (this.options[name]) {
440
- // handler.enable();
441
- // }
442
- // }
443
- // return this;
444
- // },
445
-
446
- /**
447
- * Disable chart brushing.
448
- */
449
- disableBrush() {
450
- this._chart._brushEnabled = false;
451
- this._resetDrag();
452
- },
453
-
454
- /**
455
- * Enable chart brushing.
456
- */
457
- enableBrush() {
458
- this._chart._brushEnabled = true;
459
- },
460
-
461
- /**
462
- * Disable chart zooming.
463
- */
464
- disableZoom() {
465
- this._chart._zoomEnabled = false;
466
- this._chart._resetZoom();
467
- },
468
-
469
- /**
470
- * Enable chart zooming.
471
- */
472
- enableZoom() {
473
- this._chart._zoomEnabled = true;
474
- },
475
-
476
- /**
477
- * Sets a map view that contains the given geographical bounds.
478
- */
479
- fitBounds(bounds) {
480
- bounds = bounds || this.getBounds();
481
- if (this._map && bounds.isValid()) this._map.fitBounds(bounds);
482
- },
483
-
484
- getBounds(data) {
485
- return L.latLngBounds((data || this._data).map((d) => d.latlng));
486
- },
487
-
488
- /**
489
- * Get default zoom level (followMarker: true).
490
- */
491
- getZFollow() {
492
- return this.options.zFollow;
493
- },
494
-
495
- /**
496
- * Hide current elevation chart profile.
497
- */
498
- hide() {
499
- style(this._container, "display", "none");
500
- },
501
-
502
- /**
503
- * Initialize chart control "options" and "container".
504
- */
505
- initialize(opts) {
506
-
507
- // opts = L.setOptions(this, opts);
508
-
509
- // Fixes: https://github.com/Raruto/leaflet-elevation/pull/240
510
- opts = L.setOptions(this, L.extend({}, cloneDeep(Options), opts)); // "deep copy" nested objects (multiple charts)
511
-
512
- this._data = [];
513
- this._layers = L.featureGroup();
514
- this._markers = L.featureGroup();
515
- this._hotline = L.featureGroup();
516
- this._circleMarkers = L.featureGroup();
517
- this._markedSegments = L.polyline([]);
518
- this._start = L.circleMarker([0,0], (opts.trkStart || Options.trkStart));
519
- this._end = L.circleMarker([0,0], (opts.trkEnd || Options.trkEnd));
520
- this._chartEnabled = true;
521
- this._yCoordMax = -Infinity;
522
- this.track_info = {};
523
- // this.handlers = [];
524
-
525
- if (opts.followMarker) this._setMapView = throttle(this._setMapView, 300, this);
526
- if (opts.legend) opts.margins.bottom += 30;
527
- if (opts.theme) opts.polylineSegments.className += ' ' + opts.theme;
528
- if (opts.wptIcons === true) opts.wptIcons = Options.wptIcons;
529
- if (opts.distanceMarkers === true) opts.distanceMarkers = Options.distanceMarkers;
530
- if (opts.trkStart) this._start.addTo(this._circleMarkers);
531
- if (opts.trkEnd) this._end.addTo(this._circleMarkers);
532
-
533
-
534
- this._markedSegments.setStyle(opts.polylineSegments);
535
-
536
- // Leaflet canvas renderer colors
537
- L.extend(Colors, opts.colors || {});
538
-
539
- // Various stuff
540
- this._fixCanvasPaths();
541
- this._fixTooltipSize();
542
-
543
- },
544
-
545
- /**
546
- * Javascript scripts downloader (lazy loader)
547
- */
548
- import(src, condition) {
549
- if (Array.isArray(src)) {
550
- return Promise.all(src.map(m => this.import(m)));
551
- }
552
- switch(src) {
553
- case this.__D3: condition = typeof d3 !== 'object'; break;
554
- case this.__TOGEOJSON: condition = typeof toGeoJSON !== 'object'; break;
555
- case this.__LGEOMUTIL: condition = typeof L.GeometryUtil !== 'object'; break;
556
- case this.__LALMOSTOVER: condition = typeof L.Handler.AlmostOver !== 'function'; break;
557
- case this.__LDISTANCEM: condition = typeof L.DistanceMarkers !== 'function'; break;
558
- case this.__LEDGESCALE: condition = typeof L.Control.EdgeScale !== 'function'; break;
559
- case this.__LHOTLINE: condition = typeof L.Hotline !== 'function'; break;
560
- }
561
- return condition !== false ? import(resolveURL(src, this.options.srcFolder)) : Promise.resolve();
562
- },
563
-
564
- /**
565
- * Load elevation data (GPX, GeoJSON, KML or TCX).
566
- */
567
- load(data) {
568
- this._parseFromString(data).then( geojson => geojson ? this._loadLayer(geojson) : this._loadFile(data));
569
- },
570
-
571
- /**
572
- * Create container DOM element and related event listeners.
573
- * Called on control.addTo(map).
574
- */
575
- onAdd(map) {
576
- this._map = map;
577
-
578
- let container = this._container = create("div", "elevation-control " + this.options.theme + " " + (this.options.detached ? 'elevation-detached' : 'leaflet-control'), this.options.detached ? { id: 'elevation-' + randomId() } : {});
579
-
580
- if (!this.eleDiv) this.eleDiv = container;
581
-
582
- this._loadModules(this.options.handlers).then(() => { // Inject here required modules (data handlers)
583
- this._initChart(container);
584
- this._initButton(container);
585
- this._initSummary(container);
586
- this._initMarker(map);
587
- this._initLayer(map);
588
- this._modulesLoaded = true;
589
- this.fire('modules_loaded');
590
- });
591
-
592
- this.fire('add');
593
-
594
- return container;
595
- },
596
-
597
- /**
598
- * Clean up control code and related event listeners.
599
- * Called on control.remove().
600
- */
601
- onRemove(map) {
602
- this._container = null;
603
-
604
- map
605
- .off('zoom viewreset zoomanim', this._hideMarker, this)
606
- .off('resize', this._resetView, this)
607
- .off('resize', this._resizeChart, this)
608
- .off('mousedown', this._resetDrag, this);
609
-
610
- off(map.getContainer(), 'mousewheel', this._resetDrag, this);
611
- off(map.getContainer(), 'touchstart', this._resetDrag, this);
612
- off(document, 'keydown', this._onKeyDown, this);
613
-
614
- this
615
- .off('eledata_added eledata_loaded', this._updateChart, this)
616
- .off('eledata_added eledata_loaded', this._updateSummary, this);
617
-
618
- this.fire('remove');
619
- },
620
-
621
- /**
622
- * Redraws the chart control. Sometimes useful after screen resize.
623
- */
624
- redraw() {
625
- this._resizeChart();
626
- },
627
-
628
- /**
629
- * Set default zoom level (followMarker: true).
630
- */
631
- setZFollow(zoom) {
632
- this.options.zFollow = zoom;
633
- },
634
-
635
- /**
636
- * Hide current elevation chart profile.
637
- */
638
- show() {
639
- style(this._container, "display", "block");
640
- },
641
-
642
- /*
643
- * Parsing data either from GPX or GeoJSON and update the diagram data
644
- */
645
- _addData(d) {
646
- if (!d) {
647
- return;
648
- }
649
-
650
- // Standard GeoJSON
651
- if (d.type === "FeatureCollection" ) {
652
- return each(d.features, feature => this._addData(feature));
653
- } else if (d.type === "Feature") {
654
- let geom = d.geometry;
655
- if (geom) {
656
- switch (geom.type) {
657
- case 'LineString': return this._addGeoJSONData(geom.coordinates, d.properties);
658
- case 'MultiLineString': return each(geom.coordinates, (coords, i) => this._addGeoJSONData(coords, d.properties, i));
659
- case 'Point':
660
- default: return console.warn('Unsopperted GeoJSON feature geometry type:' + geom.type);
661
- }
662
- }
663
- }
664
-
665
- // Fallback for leaflet layers (eg. L.Gpx)
666
- if (d._latlngs) {
667
- return this._addGeoJSONData(d._latlngs, d.feature && d.feature.properties);
668
- }
669
-
670
- },
671
-
672
- /*
673
- * Parsing of GeoJSON data lines and their elevation in z-coordinate
674
- */
675
- _addGeoJSONData(coords, properties, nestingLevel) {
676
-
677
- // "coordinateProperties" property is generated inside "@tmcw/toGeoJSON"
678
- let props = (properties && properties.coordinateProperties) || properties;
679
-
680
- coords.forEach((point, i) => {
681
-
682
- // GARMIN_EXTENSIONS = ["hr", "cad", "atemp", "wtemp", "depth", "course", "bearing"];
683
- point.meta = point.meta ?? { time: null, ele: null };
684
-
685
- point.prev = (attr) => (attr ? this._data[i > 0 ? i - 1 : 0][attr] : this._data[i > 0 ? i - 1 : 0]);
686
-
687
- this.fire("elepoint_init", { point: point, props: props, id: i, isMulti: nestingLevel });
688
-
689
- this._addPoint(
690
- point.lat ?? point[1],
691
- point.lng ?? point[0],
692
- point.alt ?? point.meta.ele ?? point[2]
693
- );
694
-
695
- this.fire("elepoint_added", { point: point, index: this._data.length - 1 });
696
-
697
- if (this._yCoordMax < this._data[this._data.length - 1][this.options.yAttr]) this._yCoordMax = this._data[this._data.length - 1][this.options.yAttr];
698
- });
699
-
700
- this.fire("eletrack_added", { coords: coords, index: this._data.length - 1 });
701
- },
702
-
703
- /*
704
- * Parse and push a single (x, y, z) point to current elevation profile.
705
- */
706
- _addPoint(x, y, z) {
707
- if (this.options.reverseCoords) {
708
- [x, y] = [y, x];
709
- }
710
-
711
- this._data.push({
712
- x: x,
713
- y: y,
714
- z: z,
715
- latlng: L.latLng(x, y, z)
716
- });
717
-
718
- this.fire("eledata_updated", { index: this._data.length - 1 });
719
- },
720
-
721
- _addLayer(layer) {
722
- if (layer) this._layers.addLayer(layer);
723
- // Postpone adding the distance markers (lazy: true)
724
- if (layer && this.options.distanceMarkers && this.options.distanceMarkers.lazy) {
725
- layer.on('add remove', ({target, type}) => L.DistanceMarkers && target instanceof L.Polyline && target[type + 'DistanceMarkers']());
726
- }
727
- return layer;
728
- },
729
-
730
- _addMarker(marker) {
731
- if (marker) this._markers.addLayer(marker);
732
- return marker;
733
- },
734
-
735
- /**
736
- * Initialize "L.AlmostOver" integration
737
- */
738
- _initAlmostOverHandler(map, layer) {
739
- return (map && this.options.almostOver && !L.Browser.mobile) ? this.import([this.__LGEOMUTIL, this.__LALMOSTOVER])
740
- .then(() => {
741
- map.addHandler('almostOver', L.Handler.AlmostOver);
742
- if (L.GeometryUtil && map.almostOver && map.almostOver.enabled()) {
743
- map.almostOver.addLayer(layer);
744
- map
745
- .on('almost:move', this._onMouseMoveLayer, this)
746
- .on('almost:out', this._onMouseOut, this);
747
- this.once('eledata_clear', () => {
748
- map.almostOver.removeLayer(layer);
749
- map
750
- .off('almost:move', this._onMouseMoveLayer, this)
751
- .off('almost:out', this._onMouseOut, this);
752
- });
753
- }
754
- }) : Promise.resolve();
755
- },
756
-
757
- /**
758
- * Initialize "L.DistanceMarkers" integration
759
- */
760
- _initDistanceMarkers() {
761
- return this.options.distanceMarkers ? this.import([this.__LGEOMUTIL, this.__LDISTANCEM]) : Promise.resolve();
762
- },
763
-
764
- /**
765
- * Initialize "L.Control.EdgeScale" integration
766
- */
767
- _initEdgeScale(map) {
768
- return this.options.edgeScale ? this.import(this.__LEDGESCALE)
769
- .then(() => {
770
- map.edgeScaleControl = map.edgeScaleControl || L.control.edgeScale('boolean' !== typeof this.options.edgeScale ? this.options.edgeScale : {}).addTo(map);
771
- }) : Promise.resolve();
772
- },
773
-
774
- _initHotLine(layer) {
775
- let prop = typeof this.options.hotline == 'string' ? this.options.hotline : 'elevation';
776
- return this.options.hotline ? this.import(this.__LHOTLINE)
777
- .then(() => {
778
- layer.eachLayer((trkseg) => {
779
- if (trkseg.feature.geometry.type != "Point") {
780
- let geo = L.geoJson(trkseg.toGeoJSON(), { coordsToLatLng: (coords) => L.latLng(coords[0], coords[1], coords[2] * (this.options.altitudeFactor || 1))});
781
- let line = L.hotline(geo.toGeoJSON().features[0].geometry.coordinates, {
782
- renderer: L.Hotline.renderer(),
783
- min: isFinite(this.track_info[prop + '_min']) ? this.track_info[prop + '_min'] : 0,
784
- max: isFinite(this.track_info[prop + '_max']) ? this.track_info[prop + '_max'] : 1,
785
- palette: {
786
- 0.0: '#008800',
787
- 0.5: '#ffff00',
788
- 1.0: '#ff0000'
789
- },
790
- weight: 5,
791
- outlineColor: '#000000',
792
- outlineWidth: 1
793
- }).addTo(this._hotline);
794
- let alpha = trkseg.options.style && trkseg.options.style.opacity || 1;
795
- trkseg.on('add remove', ({type}) => {
796
- trkseg.setStyle({opacity: (type == 'add' ? 0 : alpha)});
797
- line[(type == 'add' ? 'addTo' : 'removeFrom')](trkseg._map);
798
- if (line._renderer) line._renderer._container.parentElement.insertBefore(line._renderer._container, line._renderer._container.parentElement.firstChild);
799
- });
800
- }
801
- });
802
- }) : Promise.resolve();
803
- },
804
-
805
- /**
806
- * Initialize "L.AlmostOver" and "L.DistanceMarkers"
807
- */
808
- _initMapIntegrations(layer) {
809
- let map = this._map;
810
- if (map) {
811
- if (this._data.length) {
812
- this._start.setLatLng(this._data[0].latlng);
813
- this._end.setLatLng(this._data[this._data.length -1].latlng);
814
- }
815
- Promise.all([
816
- this._initHotLine(layer),
817
- this._initAlmostOverHandler(map, layer),
818
- this._initDistanceMarkers(),
819
- this._initEdgeScale(map),
820
- ]).then(() => {
821
- if (this.options.polyline) {
822
- this._layers.addLayer(layer.addTo(map)); // hotfix for: https://github.com/Raruto/leaflet-elevation/issues/233
823
- this._circleMarkers.addTo(map);
824
- }
825
- if (this.options.autofitBounds) {
826
- this.fitBounds(layer.getBounds());
827
- }
828
- map.invalidateSize();
829
- });
830
- } else {
831
- this.once('add', () => this._initMapIntegrations(layer));
832
- }
833
- },
834
-
835
- /*
836
- * Collapse current chart control.
837
- */
838
- _collapse() {
839
- replaceClass(this._container, 'elevation-expanded', 'elevation-collapsed');
840
- if (this._map) this._map.invalidateSize();
841
- },
842
-
843
- /*
844
- * Expand current chart control.
845
- */
846
- _expand() {
847
- replaceClass(this._container, 'elevation-collapsed', 'elevation-expanded');
848
- if (this._map) this._map.invalidateSize();
849
- },
850
-
851
- /**
852
- * Add some basic colors to leaflet canvas renderer (preferCanvas: true).
853
- */
854
- _fixCanvasPaths() {
855
- let oldProto = L.Canvas.prototype._fillStroke;
856
- let control = this;
857
-
858
- let theme = this.options.theme.split(' ')[0].replace('-theme', '');
859
- let color = Colors[theme] || {};
860
-
861
- L.Canvas.include({
862
- _fillStroke(ctx, layer) {
863
- if (control._layers.hasLayer(layer)) {
864
-
865
- let options = layer.options;
866
-
867
- options.color = color.line || color.area || theme;
868
- options.stroke = !!options.color;
869
-
870
- oldProto.call(this, ctx, layer);
871
-
872
- if (options.stroke && options.weight !== 0) {
873
- let oldVal = ctx.globalCompositeOperation || 'source-over';
874
- ctx.globalCompositeOperation = 'destination-over';
875
- ctx.strokeStyle = color.outline || '#FFF';
876
- ctx.lineWidth = options.weight * 1.75;
877
- ctx.stroke();
878
- ctx.globalCompositeOperation = oldVal;
879
- }
880
-
881
- } else {
882
- oldProto.call(this, ctx, layer);
883
- }
884
- }
885
- });
886
- },
887
-
888
- /**
889
- * Partial fix for initial tooltip size
890
- *
891
- * @link https://github.com/Raruto/leaflet-elevation/issues/81#issuecomment-713477050
892
- */
893
- _fixTooltipSize() {
894
- this.on('elechart_init', () =>
895
- this.once('elechart_change elechart_hover', ({data, xCoord}) => {
896
- if (this._chartEnabled) {
897
- this._chart._showDiagramIndicator(data, xCoord);
898
- this._chart._showDiagramIndicator(data, xCoord);
899
- }
900
- this._updateMarker(data);
901
- })
902
- );
903
- },
904
-
905
- /*
906
- * Finds a data entry for the given LatLng
907
- */
908
- _findItemForLatLng(latlng) {
909
- return this._data[this._chart._findIndexForLatLng(latlng)];
910
- },
911
-
912
- /*
913
- * Finds a data entry for the given xDiagCoord
914
- */
915
- _findItemForX(x) {
916
- return this._data[this._chart._findIndexForXCoord(x)];
917
- },
918
-
919
- /**
920
- * Fires an event of the specified type.
921
- */
922
- _fireEvt(type, data, propagate) {
923
- if (this.fire) this.fire(type, data, propagate);
924
- if (this._map) this._map.fire(type, data, propagate);
925
- },
926
-
927
- /*
928
- * Hides the position/height indicator marker drawn onto the map
929
- */
930
- _hideMarker() {
931
- if (this.options.autohideMarker) {
932
- this._marker.remove();
933
- }
934
- },
935
-
936
- /**
937
- * Generate "svg" chart (DOM element).
938
- */
939
- _initChart(container) {
940
- let opts = this.options;
941
- let map = this._map;
942
-
943
- if (opts.detached) {
944
- let { offsetWidth, offsetHeight} = this.eleDiv;
945
- if (offsetWidth > 0) opts.width = offsetWidth;
946
- if (offsetHeight > 20) opts.height = offsetHeight - 20; // 20 = horizontal scrollbar size.
947
- } else {
948
- let { clientWidth } = map.getContainer();
949
- opts._maxWidth = opts._maxWidth > opts.width ? opts._maxWidth : opts.width;
950
- this._container.style.maxWidth = opts._maxWidth + 'px';
951
- if (opts._maxWidth > clientWidth) opts.width = clientWidth - 30;
952
- }
953
-
954
- this
955
- .import([this.__D3, this.__LCHART])
956
- .then((m) => {
957
-
958
- let chart = this._chart = new (m[1] || Elevation).Chart(opts, this);
959
-
960
- this._x = this._chart._x;
961
- this._y = this._chart._y;
962
-
963
- d3
964
- .select(container)
965
- .call(chart.render());
966
-
967
- chart
968
- .on('reset_drag', this._hideMarker, this)
969
- .on('mouse_enter', this._onMouseEnter, this)
970
- .on('dragged', this._onDragEnd, this)
971
- .on('mouse_move', this._onMouseMove, this)
972
- .on('mouse_out', this._onMouseOut, this)
973
- .on('ruler_filter', this._onRulerFilter, this)
974
- .on('zoom', this._updateChart, this)
975
- .on('elepath_toggle', this._onToggleChart, this)
976
- .on('margins_updated', this._resizeChart, this);
977
-
978
-
979
- this.fire("elechart_init");
980
-
981
- map
982
- .on('zoom viewreset zoomanim', this._hideMarker, this)
983
- .on('resize', this._resetView, this)
984
- .on('resize', this._resizeChart, this)
985
- .on('rotate', this._rotateMarker, this)
986
- .on('mousedown', this._resetDrag, this);
987
-
988
- on(map.getContainer(), 'mousewheel', this._resetDrag, this);
989
- on(map.getContainer(), 'touchstart', this._resetDrag, this);
990
- on(document, 'keydown', this._onKeyDown, this);
991
-
992
- this
993
- .on('eledata_added eledata_loaded', this._updateChart, this)
994
- .on('eledata_added eledata_loaded', this._updateSummary, this);
995
-
996
- this._updateChart();
997
- this._updateSummary();
998
- });
999
-
1000
-
1001
- },
1002
-
1003
- _initLayer() {
1004
- this._layers
1005
- .on('layeradd layerremove', ({layer, type}) => {
1006
- let node = layer.getElement && layer.getElement();
1007
- toggleClass(node, this.options.polyline.className + ' ' + this.options.theme, type == 'layeradd');
1008
- toggleEvent(layer, "mousemove", this._onMouseMoveLayer.bind(this), type == 'layeradd');
1009
- toggleEvent(layer, "mouseout", this._onMouseOut.bind(this), type == 'layeradd');
1010
- });
1011
- },
1012
-
1013
- _initMarker(map) {
1014
- let pane = map.getPane('elevationPane');
1015
- if (!pane) {
1016
- pane = this._pane = map.createPane('elevationPane', map.getPane('norotatePane') || map.getPane('mapPane'));
1017
- pane.style.zIndex = 625; // This pane is above markers but below popups.
1018
- pane.style.pointerEvents = 'none';
1019
- }
1020
-
1021
- if (this._renderer) this._renderer.remove();
1022
- this._renderer = L.svg({ pane: "elevationPane" }).addTo(this._map); // default leaflet svg renderer
1023
-
1024
- this.import([this.__D3, this.__LMARKER])
1025
- .then((m) => {
1026
- this._marker = new (m[1] || Elevation).Marker(this.options, this);
1027
- this.fire("elechart_marker");
1028
- });
1029
- },
1030
-
1031
- /**
1032
- * Inspired by L.Control.Layers
1033
- */
1034
- _initButton(container) {
1035
- L.DomEvent
1036
- .disableClickPropagation(container)
1037
- .disableScrollPropagation(container);
1038
-
1039
- this.options.collapsed ? this._collapse() : this._expand();
1040
-
1041
- if (this.options.autohide) {
1042
- on(container, 'mouseover', this._expand, this);
1043
- on(container, 'mouseout', this._collapse, this);
1044
- this._map.on('click', this._collapse, this);
1045
- }
1046
-
1047
- if (this.options.closeBtn) {
1048
- let link = this._button = create('a', "elevation-toggle-icon", { href: '#', title: L._('Elevation'), }, container);
1049
- on(link, 'click', L.DomEvent.stop);
1050
- on(link, 'click', this._toggle, this);
1051
- on(link, 'focus', this._toggle, this);
1052
- fetch(resolveURL(this.__btnIcon, this.options.srcFolder)).then(r => r.ok && r.text().then(img => link.innerHTML = img));
1053
- }
1054
- },
1055
-
1056
- _initSummary(container) {
1057
- this.import(this.__LSUMMARY).then((m)=>{
1058
- this._summary = new (m || Elevation).Summary({ summary: this.options.summary }, this);
1059
-
1060
- this.on('elechart_init', () => {
1061
- d3.select(container).call(this._summary.render());
1062
- });
1063
- });
1064
- },
1065
-
1066
- /**
1067
- * Retrieve data from a remote url (HTTP).
1068
- */
1069
- _loadFile(url) {
1070
- fetch(url)
1071
- .then((response) => response.text())
1072
- .then((data) => {
1073
- this._downloadURL = url; // TODO: handle multiple urls?
1074
- this._parseFromString(data)
1075
- .then( geojson => geojson && this._loadLayer(geojson));
1076
- }).catch((err) => console.warn(err));
1077
- },
1078
-
1079
- /**
1080
- * Dynamically import only required javascript modules (code splitting)
1081
- */
1082
- _loadModules(handlers) {
1083
- // First map known classnames (eg. "Altitude" --> L.Control.Elevation.Altitude)
1084
- handlers = handlers.map((h) => typeof h === 'string' && typeof Elevation[h] !== "undefined" ? Elevation[h] : h);
1085
- // Then load optional classes and custom imports (eg. "Cadence" --> import('../src/handlers/cadence.js'))
1086
- let modules = handlers.map(file => (typeof file === 'string' && this.import(this.__modulesFolder + file.toLowerCase() + '.js')) || (file instanceof Promise && file) || Promise.resolve());
1087
- return Promise.all(modules).then((m) => {
1088
- each(m, (exported, i) => {
1089
- let fn = exported && Object.keys(exported)[0];
1090
- if (fn) {
1091
- handlers[i] = Elevation[fn] = (Elevation[fn] ?? exported[fn]);
1092
- }
1093
- });
1094
- each(handlers, h => ["function", "object"].includes(typeof h) && this._registerHandler(h));
1095
- });
1096
- },
1097
-
1098
- /**
1099
- * Simple GeoJSON data loader (L.GeoJSON).
1100
- */
1101
- _loadLayer(geojson) {
1102
- let { polyline, theme, waypoints, wptIcons, wptLabels, distanceMarkers } = this.options;
1103
- let style = L.extend({}, polyline);
1104
-
1105
- if (theme) {
1106
- style.className += ' ' + theme;
1107
- }
1108
-
1109
- if (geojson.name) {
1110
- this.track_info.name = geojson.name;
1111
- }
1112
-
1113
- let layer = L.geoJson(geojson, {
1114
- distanceMarkers: distanceMarkers,
1115
- style: style,
1116
- pointToLayer: (feature, latlng) => {
1117
- if (waypoints) {
1118
- let { desc, name, sym } = feature.properties;
1119
- desc = desc || '';
1120
- name = name || '';
1121
- // Handle chart waypoints (dots)
1122
- if ([true, 'dots'].includes(waypoints)) {
1123
- this._registerCheckPoint({
1124
- latlng: latlng,
1125
- label : ([true, 'dots'].includes(wptLabels) ? name : '')
1126
- });
1127
- }
1128
- // Handle map waypoints (markers)
1129
- if ([true, 'markers'].includes(waypoints) && wptIcons != false) {
1130
- return this._registerMarker({
1131
- latlng : latlng,
1132
- sym : (sym ?? name).replace(/["']/g, '').replace(/ /g, '-').toLowerCase(),
1133
- content: [true, 'markers'].includes(wptLabels) && (name || desc) && decodeURI("<b>" + name + "</b>" + (desc.length > 0 ? '<br>' + desc : ''))
1134
- });
1135
- }
1136
- }
1137
- },
1138
- onEachFeature: (feature, layer) => feature.geometry && feature.geometry.type != 'Point' && this.addData(feature, layer),
1139
- });
1140
-
1141
- this.import(this.__D3).then(() => {
1142
- this._initMapIntegrations(layer);
1143
- const event_data = { data: geojson, layer: layer, name: this.track_info.name, track_info: this.track_info };
1144
- if (this._modulesLoaded) {
1145
- this._fireEvt("eledata_loaded", event_data);
1146
- } else {
1147
- this.once('modules_loaded', () => this._fireEvt("eledata_loaded", event_data));
1148
- }
1149
- });
1150
-
1151
- return layer;
1152
- },
1153
-
1154
- _onDragEnd({ dragstart, dragend}) {
1155
- this._hideMarker();
1156
- this.fitBounds(L.latLngBounds([dragstart.latlng, dragend.latlng]));
1157
-
1158
- this.fire("elechart_dragged");
1159
- },
1160
-
1161
- _onKeyDown({key}) {
1162
- if (!this.options.detached && key === "Escape"){
1163
- this._collapse();
1164
- } },
1165
-
1166
- /**
1167
- * Trigger mouseenter event.
1168
- */
1169
- _onMouseEnter() {
1170
- this.fire('elechart_enter');
1171
- },
1172
-
1173
- /*
1174
- * Handles the moueseover the chart and displays distance and altitude level.
1175
- */
1176
- _onMouseMove({xCoord}) {
1177
- if (this._chartEnabled && this._data.length) {
1178
- let item = this._findItemForX(xCoord);
1179
- if (item) {
1180
- if (this._chartEnabled) this._chart._showDiagramIndicator(item, xCoord);
1181
-
1182
- this._updateMarker(item);
1183
- this._setMapView(item);
1184
-
1185
- if (this._map) {
1186
- addClass(this._map.getContainer(), 'elechart-hover');
1187
- }
1188
-
1189
- this.fire("elechart_change", { data: item, xCoord: xCoord });
1190
- this.fire("elechart_hover", { data: item, xCoord: xCoord });
1191
- }
1192
- }
1193
- },
1194
-
1195
- /*
1196
- * Handles mouseover events of the data layers on the map.
1197
- */
1198
- _onMouseMoveLayer({latlng}) {
1199
- if (this._data.length) {
1200
- let item = this._findItemForLatLng(latlng);
1201
- if (item) {
1202
- let xCoord = item.xDiagCoord;
1203
-
1204
- if (this._chartEnabled) this._chart._showDiagramIndicator(item, xCoord);
1205
-
1206
- this._updateMarker(item);
1207
-
1208
- this.fire("elechart_change", { data: item, xCoord: xCoord });
1209
- }
1210
- }
1211
- },
1212
-
1213
- /*
1214
- * Handles the moueseout over the chart.
1215
- */
1216
- _onMouseOut() {
1217
- if (!this.options.detached) {
1218
- this._hideMarker();
1219
- this._chart._hideDiagramIndicator();
1220
- }
1221
-
1222
- if (this._map) {
1223
- removeClass(this._map.getContainer(), 'elechart-hover');
1224
- }
1225
-
1226
- this.fire("elechart_leave");
1227
- },
1228
-
1229
- /**
1230
- * Handles the drag event over the ruler filter.
1231
- */
1232
- _onRulerFilter({coords}) {
1233
- this._updateMapSegments(coords);
1234
- },
1235
-
1236
- /**
1237
- * Toggle chart data on legend click
1238
- */
1239
- _onToggleChart({ name, enabled }) {
1240
-
1241
- this._chartEnabled = this._chart._hasActiveLayers();
1242
-
1243
- // toggle layer visibility on empty chart
1244
- this._layers.eachLayer(layer => toggleClass(layer.getElement && layer.getElement(), this.options.polyline.className + ' ' + this.options.theme, this._chartEnabled));
1245
-
1246
- // toggle option value (eg. altitude = { 'disabled' || 'enabled' })
1247
- this.options[name] = !enabled && this.options[name] == 'disabled' ? 'enabled' : 'disabled';
1248
-
1249
- // remove marker on empty chart
1250
- if (!this._chartEnabled) {
1251
- this._chart._hideDiagramIndicator();
1252
- this._marker.remove();
1253
- }
1254
- },
1255
-
1256
- /**
1257
- * Simple GeoJSON Parser
1258
- */
1259
- _parseFromGeoJSONString(data) {
1260
- try {
1261
- return JSON.parse(data);
1262
- } catch (e) { }
1263
- },
1264
-
1265
- /**
1266
- * Attempt to parse raw response data (GeoJSON or XML > GeoJSON)
1267
- */
1268
- _parseFromString(data) {
1269
- return new Promise(resolve =>
1270
- this.import(this.__TOGEOJSON).then(() => {
1271
- let geojson;
1272
- try {
1273
- geojson = this._parseFromXMLString(data.trim());
1274
- } catch (e) {
1275
- geojson = this._parseFromGeoJSONString(data.toString());
1276
- }
1277
- if (geojson) {
1278
- geojson.name = geojson.name || (this._downloadURL || '').split('/').pop().split('#')[0].split('?')[0];
1279
- }
1280
- resolve(geojson);
1281
- })
1282
- );
1283
- },
1284
-
1285
- /**
1286
- * Simple XML Parser (GPX, KML, TCX)
1287
- */
1288
- _parseFromXMLString(data) {
1289
- if (data.indexOf("<") != 0) {
1290
- throw 'Invalid XML';
1291
- }
1292
- let xml = (new DOMParser()).parseFromString(data, "text/xml");
1293
- let type = xml.documentElement.tagName.toLowerCase(); // "kml" or "gpx"
1294
- let name = xml.getElementsByTagName('name');
1295
- if (xml.getElementsByTagName('parsererror').length) {
1296
- throw 'Invalid XML';
1297
- }
1298
- if (!(type in toGeoJSON)) {
1299
- type = xml.documentElement.tagName == "TrainingCenterDatabase" ? 'tcx' : 'gpx';
1300
- }
1301
- let geojson = toGeoJSON[type](xml);
1302
- geojson.name = name.length > 0 ? (Array.from(name).find(tag => tag.parentElement.tagName == "trk") ?? name[0]).textContent : '';
1303
- return geojson;
1304
- },
1305
-
1306
- /**
1307
- * Add chart profile to diagram
1308
- */
1309
- _registerAreaPath(props) {
1310
- this.on("elechart_init", () => this._chart._registerAreaPath(props));
1311
- },
1312
-
1313
- /**
1314
- * Add chart grid to diagram
1315
- */
1316
- _registerAxisGrid(props) {
1317
- this.on("elechart_axis", () => this._chart._registerAxisGrid(props));
1318
- },
1319
-
1320
- /**
1321
- * Add chart axis to diagram
1322
- */
1323
- _registerAxisScale(props) {
1324
- this.on("elechart_axis", () => this._chart._registerAxisScale(props));
1325
- },
1326
-
1327
- /**
1328
- * Add a point of interest over the diagram
1329
- */
1330
- _registerCheckPoint(props) {
1331
- const cb = () => this._chart._registerCheckPoint(props);
1332
- this
1333
- .on("elechart_updated", cb)
1334
- .once("eledata_clear", () => this.off("elechart_updated", cb));
1335
- },
1336
-
1337
- /**
1338
- * Base handler for iterative track statistics (dist, time, z, slope, speed, acceleration, ...)
1339
- */
1340
- _registerDataAttribute(props) {
1341
-
1342
- // parse of "coordinateProperties" for later usage
1343
- if (props.coordPropsToMeta) {
1344
- this.on("elepoint_init", (e) => props.coordPropsToMeta.call(this, e));
1345
- }
1346
-
1347
- // prevent excessive variabile instanstations
1348
- let i, curr, prev, attr = props.attr || props.name;
1349
-
1350
- // save here a reference to last used point
1351
- let lastValid = {};
1352
-
1353
- // iteration
1354
- this.on("elepoint_added", ({index, point}) => {
1355
- i = index;
1356
-
1357
- prev = curr ?? this._data[i]; // same as: this._data[i > 0 ? i - 1 : i]
1358
- curr = this._data[i];
1359
-
1360
- // retrieve point value
1361
- curr[attr] = props.pointToAttr.call(this, point, i);
1362
-
1363
- // check and fix missing data on last added point
1364
- if (i > 0 && isNaN(prev[attr])) {
1365
- if (!isNaN(lastValid[attr]) && !isNaN(curr[attr])) {
1366
- prev[attr] = (lastValid[attr] + curr[attr]) / 2;
1367
- } else if (!isNaN(lastValid[attr])) {
1368
- prev[attr] = lastValid[attr];
1369
- } else if (!isNaN(curr[attr])) {
1370
- prev[attr] = curr[attr];
1371
- }
1372
- // update "yAttr" and "xAttr"
1373
- if (props.meta) {
1374
- prev[props.meta] = prev[attr];
1375
- }
1376
- }
1377
-
1378
- // skip to next iteration for invalid or missing data (eg. i == 0)
1379
- if (isNaN(curr[attr])) {
1380
- return;
1381
- }
1382
-
1383
- // update reference to last used point
1384
- lastValid[attr] = curr[attr];
1385
-
1386
- // Limit "crazy" delta values.
1387
- if (props.deltaMax) {
1388
- curr[attr] =wrapDelta(curr[attr], prev[attr], props.deltaMax);
1389
- }
1390
-
1391
- // Range of acceptable values.
1392
- if (props.clampRange) {
1393
- curr[attr] = clamp(curr[attr], props.clampRange);
1394
- }
1395
-
1396
- // Limit floating point precision.
1397
- if (!isNaN(props.decimals)) {
1398
- curr[attr] = round(curr[attr], props.decimals);
1399
- }
1400
-
1401
- // update "track_info" stats (min, max, avg, ...)
1402
- if (props.stats) {
1403
- for (const key in props.stats) {
1404
- let sname = (props.statsName || attr) + (key != '' ? '_' : '');
1405
- this.track_info[sname + key] = props.stats[key].call(this, curr[attr], this.track_info[sname + key], this._data.length);
1406
- }
1407
- }
1408
-
1409
- // update here some mixins (eg. complex "track_info" stuff)
1410
- if (props.onPointAdded) props.onPointAdded.call(this, curr[attr], i, point);
1411
- });
1412
- },
1413
-
1414
- /**
1415
- * Parse a module definition and attach related function listeners
1416
- */
1417
- _registerHandler(props) {
1418
-
1419
- // eg. L.Control.Altitude
1420
- if (typeof props === "function") {
1421
- return this._registerHandler(props.call(this));
1422
- }
1423
-
1424
- let {
1425
- name,
1426
- attr,
1427
- required,
1428
- deltaMax,
1429
- clampRange,
1430
- decimals,
1431
- meta,
1432
- unit,
1433
- coordinateProperties,
1434
- coordPropsToMeta: coordPropsToMeta$1,
1435
- pointToAttr,
1436
- onPointAdded,
1437
- stats,
1438
- statsName,
1439
- grid,
1440
- scale,
1441
- path,
1442
- tooltip,
1443
- summary
1444
- } = props;
1445
-
1446
- // eg. "altitude" == true
1447
- if (this.options[name] || required) {
1448
-
1449
- this._registerDataAttribute({
1450
- name,
1451
- attr,
1452
- meta,
1453
- deltaMax,
1454
- clampRange,
1455
- decimals,
1456
- coordPropsToMeta: coordPropsToMeta(coordinateProperties, meta || name, coordPropsToMeta$1),
1457
- pointToAttr,
1458
- onPointAdded,
1459
- stats,
1460
- statsName,
1461
- });
1462
-
1463
- if (grid) {
1464
- this._registerAxisGrid(L.extend({ name }, grid));
1465
- }
1466
-
1467
- if (this.options[name] !== "summary") {
1468
- if (scale) this._registerAxisScale(L.extend({ name, label: unit }, scale));
1469
- if (path) this._registerAreaPath(L.extend({ name }, path));
1470
- }
1471
-
1472
- if (tooltip || props.tooltips) {
1473
- each([tooltip, ...(props.tooltips || [])], t => t && this._registerTooltip(L.extend({ name }, t)));
1474
- }
1475
-
1476
- if (summary) {
1477
- each(summary, (s, k) => summary[k] = L.extend({ unit }, s));
1478
- this._registerSummary(summary);
1479
- }
1480
- }
1481
- },
1482
-
1483
- _registerMarker({latlng, sym, content}) {
1484
- let { wptIcons } = this.options;
1485
- // generate and cache appropriate icon symbol
1486
- if (!wptIcons.hasOwnProperty(sym)) {
1487
- wptIcons[sym] = L.divIcon(L.extend({}, wptIcons[""].options, { html: '<i class="elevation-waypoint-icon ' + sym + '"></i>' } ));
1488
- }
1489
- let marker = L.marker(latlng, { icon: wptIcons[sym] });
1490
- if (content) {
1491
- marker.bindPopup(content, { className: 'elevation-popup', keepInView: true }).openPopup();
1492
- marker.bindTooltip(content, { className: 'elevation-tooltip', direction: 'auto', sticky: true, opacity: 1 }).openTooltip();
1493
- }
1494
- return this._addMarker(marker)
1495
- },
1496
-
1497
- /**
1498
- * Add chart or marker tooltip info
1499
- */
1500
- _registerTooltip(props) {
1501
- props.chart && this.on("elechart_init", () => this._chart._registerTooltip(L.extend({}, props, { value: props.chart })));
1502
- props.marker && this.on("elechart_marker", () => this._marker._registerTooltip(L.extend({}, props, { value: props.marker })));
1503
- },
1504
-
1505
- /**
1506
- * Add summary info to diagram
1507
- */
1508
- _registerSummary(props) {
1509
- this.on('elechart_summary', () => this._summary._registerSummary(props));
1510
- },
1511
-
1512
- /*
1513
- * Removes the drag rectangle and zoms back to the total extent of the data.
1514
- */
1515
- _resetDrag() {
1516
- this._chart._resetDrag();
1517
- this._hideMarker();
1518
- },
1519
-
1520
- /**
1521
- * Resets drag, marker and bounds.
1522
- */
1523
- _resetView() {
1524
- if (this._map && this._map._isFullscreen) return;
1525
- this._resetDrag();
1526
- this._hideMarker();
1527
- if (this.options.autofitBounds) {
1528
- this.fitBounds();
1529
- }
1530
- },
1531
-
1532
- /**
1533
- * Hacky way for handling chart resize. Deletes it and redraw chart.
1534
- */
1535
- _resizeChart() {
1536
- if (this._container && style(this._container, "display") != "none") {
1537
- let opts = this.options;
1538
- let newWidth = opts.detached ? (this.eleDiv || this._container).offsetWidth : clamp(opts._maxWidth, [0, this._map.getContainer().clientWidth - 30]);
1539
- if (newWidth) {
1540
- opts.width = newWidth;
1541
- if (this._chart && this._chart._chart) {
1542
- this._chart._chart._resize(opts);
1543
- this._updateChart();
1544
- }
1545
- }
1546
- this._updateMapSegments();
1547
- }
1548
- },
1549
-
1550
- /**
1551
- * Collapse or Expand chart control.
1552
- */
1553
- _toggle() {
1554
- hasClass(this._container, "elevation-expanded") ? this._collapse() : this._expand();
1555
- },
1556
-
1557
- /**
1558
- * Update map center and zoom (followMarker: true)
1559
- */
1560
- _setMapView(item) {
1561
- if (this._map && this.options.followMarker) {
1562
- let zoom = this._map.getZoom();
1563
- let z = this.options.zFollow;
1564
- if (typeof z === "number") {
1565
- this._map.setView(item.latlng, (zoom < z ? z : zoom), { animate: true, duration: 0.25 });
1566
- } else if (!this._map.getBounds().contains(item.latlng)) {
1567
- this._map.setView(item.latlng, zoom, { animate: true, duration: 0.25 });
1568
- }
1569
- }
1570
- },
1571
-
1572
- /**
1573
- * Calculates [x, y] domain and then update chart.
1574
- */
1575
- _updateChart() {
1576
- if (this._chart && this._container) {
1577
- this.fire("elechart_axis");
1578
-
1579
- this._chart.update({ data: this._data, options: this.options });
1580
-
1581
- this._x = this._chart._x;
1582
- this._y = this._chart._y;
1583
-
1584
- this.fire('elechart_updated');
1585
- }
1586
- },
1587
-
1588
- /*
1589
- * Update the position/height indicator marker drawn onto the map
1590
- */
1591
- _updateMarker(item) {
1592
- if (this._marker) {
1593
- this._marker.update({
1594
- map : this._map,
1595
- item : item,
1596
- yCoordMax : this._yCoordMax || 0,
1597
- options : this.options
1598
- });
1599
- }
1600
- },
1601
-
1602
- /**
1603
- * Fix marker rotation on rotated maps
1604
- */
1605
- _rotateMarker() {
1606
- if (this._marker) {
1607
- this._marker.update();
1608
- }
1609
- },
1610
-
1611
- /**
1612
- * Highlight track segments on the map.
1613
- */
1614
- _updateMapSegments(coords) {
1615
- this._markedSegments.setLatLngs(coords || []);
1616
- if (coords && this._map && !this._map.hasLayer(this._markedSegments)) {
1617
- this._markedSegments.addTo(this._map);
1618
- }
1619
- },
1620
-
1621
- /**
1622
- * Update chart summary.
1623
- */
1624
- _updateSummary() {
1625
- if (this._summary) {
1626
- this._summary.reset();
1627
- if (this.options.summary) {
1628
- this.fire("elechart_summary");
1629
- this._summary.update();
1630
- }
1631
- if (this.options.downloadLink && this._downloadURL) { // TODO: generate dynamically file content instead of using static file urls.
1632
- this._summary._container.innerHTML += '<span class="download"><a href="#">' + L._('Download') + '</a></span>';
1633
- select('.download a', this._summary._container).onclick = (e) => {
1634
- e.preventDefault();
1635
- let event = { downloadLink: this.options.downloadLink, confirm: saveFile.bind(this, this._downloadURL) };
1636
- if (this.options.downloadLink == 'modal' && typeof CustomEvent === "function") {
1637
- document.dispatchEvent(new CustomEvent("eletrack_download", { detail: event }));
1638
- } else if (this.options.downloadLink == 'link' || this.options.downloadLink === true) {
1639
- event.confirm();
1640
- }
1641
- this.fire('eletrack_download', event);
1642
- };
1643
- }
1644
- }
1645
- },
1646
-
1647
-
1648
- /**
1649
- * Calculates chart width.
1650
- */
1651
- _width() {
1652
- if (this._chart) return this._chart._width();
1653
- const { width, margins } = this.options;
1654
- return width - margins.left - margins.right;
1655
- },
1656
-
1657
- /**
1658
- * Calculates chart height.
1659
- */
1660
- _height() {
1661
- if (this._chart) return this._chart._height();
1662
- const { height, margins } = this.options;
1663
- return height - margins.top - margins.bottom;
1664
- },
1665
-
1666
- });
1667
-
1668
- /*
1669
- * Copyright (c) 2019, GPL-3.0+ Project, Raruto
1670
- *
1671
- * This file is free software: you may copy, redistribute and/or modify it
1672
- * under the terms of the GNU General Public License as published by the
1673
- * Free Software Foundation, either version 2 of the License, or (at your
1674
- * option) any later version.
1675
- *
1676
- * This file is distributed in the hope that it will be useful, but
1677
- * WITHOUT ANY WARRANTY; without even the implied warranty of
1678
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1679
- * General Public License for more details.
1680
- *
1681
- * You should have received a copy of the GNU General Public License
1682
- * along with this program. If not, see .
1683
- *
1684
- * This file incorporates work covered by the following copyright and
1685
- * permission notice:
1686
- *
1687
- * Copyright (c) 2013-2016, MIT License, Felix “MrMufflon” Bache
1688
- *
1689
- * Permission to use, copy, modify, and/or distribute this software
1690
- * for any purpose with or without fee is hereby granted, provided
1691
- * that the above copyright notice and this permission notice appear
1692
- * in all copies.
1693
- *
1694
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
1695
- * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
1696
- * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
1697
- * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
1698
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
1699
- * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
1700
- * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1701
- * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1702
- */
1703
-
1704
- Elevation.Utils = _;
1705
-
1706
- L.control.elevation = (options) => new Elevation(options);
1707
-
1708
- }));
1
+ (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/utils.js
9
+ var utils_exports = {};
10
+ __export(utils_exports, {
11
+ Colors: () => Colors,
12
+ addClass: () => addClass,
13
+ append: () => append,
14
+ clamp: () => clamp,
15
+ cloneDeep: () => cloneDeep,
16
+ coordPropsToMeta: () => coordPropsToMeta,
17
+ create: () => create,
18
+ drawCanvas: () => drawCanvas,
19
+ each: () => each,
20
+ formatDate: () => formatDate,
21
+ formatTime: () => formatTime,
22
+ hasClass: () => hasClass,
23
+ iAvg: () => iAvg,
24
+ iMax: () => iMax,
25
+ iMin: () => iMin,
26
+ iSum: () => iSum,
27
+ insert: () => insert,
28
+ off: () => off,
29
+ on: () => on,
30
+ parseDate: () => parseDate,
31
+ parseNumeric: () => parseNumeric,
32
+ randomId: () => randomId,
33
+ removeClass: () => removeClass,
34
+ replaceClass: () => replaceClass,
35
+ resolveURL: () => resolveURL,
36
+ round: () => round,
37
+ saveFile: () => saveFile,
38
+ select: () => select,
39
+ setAttributes: () => setAttributes,
40
+ style: () => style,
41
+ throttle: () => throttle,
42
+ toggleClass: () => toggleClass,
43
+ toggleEvent: () => toggleEvent,
44
+ toggleStyle: () => toggleStyle,
45
+ wrapDelta: () => wrapDelta,
46
+ wrapNum: () => wrapNum
47
+ });
48
+ var Colors = {
49
+ "lightblue": { area: "#3366CC", alpha: 0.45, stroke: "#3366CC" },
50
+ "magenta": { area: "#FF005E" },
51
+ "yellow": { area: "#FF0" },
52
+ "purple": { area: "#732C7B" },
53
+ "steelblue": { area: "#4682B4" },
54
+ "red": { area: "#F00" },
55
+ "lime": { area: "#9CC222", line: "#566B13" }
56
+ };
57
+ var SEC = 1e3;
58
+ var MIN = SEC * 60;
59
+ var HOUR = MIN * 60;
60
+ var DAY = HOUR * 24;
61
+ function resolveURL(src, baseUrl) {
62
+ return new URL(src, src.startsWith("../") || src.startsWith("./") ? baseUrl : void 0).toString();
63
+ }
64
+ function formatTime(t) {
65
+ let d = Math.floor(t / DAY);
66
+ let h = Math.floor((t - d * DAY) / HOUR);
67
+ let m = Math.floor((t - d * DAY - h * HOUR) / MIN);
68
+ let s = Math.round((t - d * DAY - h * HOUR - m * MIN) / SEC);
69
+ if (s === 60) {
70
+ m++;
71
+ s = 0;
72
+ }
73
+ if (m === 60) {
74
+ h++;
75
+ m = 0;
76
+ }
77
+ if (h === 24) {
78
+ d++;
79
+ h = 0;
80
+ }
81
+ return (d ? d + "d " : "") + h.toString().padStart(2, 0) + ":" + m.toString().padStart(2, 0) + "'" + s.toString().padStart(2, 0) + '"';
82
+ }
83
+ function formatDate(format) {
84
+ if (!format) {
85
+ return (time) => new Date(time).toLocaleString().replaceAll("/", "-").replaceAll(",", " ");
86
+ } else if (format == "time") {
87
+ return (time) => new Date(time).toLocaleTimeString();
88
+ } else if (format == "date") {
89
+ return (time) => new Date(time).toLocaleDateString();
90
+ }
91
+ return (time) => format(time);
92
+ }
93
+ function saveFile(dataURI, fileName) {
94
+ let a = create("a", "", { href: dataURI, target: "_new", download: fileName || "", style: "display:none;" });
95
+ let b = document.body;
96
+ b.appendChild(a);
97
+ a.click();
98
+ b.removeChild(a);
99
+ }
100
+ function drawCanvas(ctx, path) {
101
+ path.classed("canvas-path", true);
102
+ ctx.beginPath();
103
+ ctx.moveTo(0, 0);
104
+ let p = new Path2D(path.attr("d"));
105
+ ctx.strokeStyle = path.__strokeStyle || path.attr("stroke");
106
+ ctx.fillStyle = path.__fillStyle || path.attr("fill");
107
+ ctx.lineWidth = 1.25;
108
+ ctx.globalCompositeOperation = "source-over";
109
+ ctx.globalAlpha = path.attr("stroke-opacity") || 0.3;
110
+ ctx.stroke(p);
111
+ ctx.globalAlpha = path.attr("fill-opacity") || 0.45;
112
+ ctx.fill(p);
113
+ ctx.globalAlpha = 1;
114
+ ctx.closePath();
115
+ }
116
+ function coordPropsToMeta(coordProps, name, parser) {
117
+ return coordProps && (({ props, point, id, isMulti }) => {
118
+ if (props) {
119
+ for (const key of coordProps) {
120
+ if (key in props) {
121
+ point.meta[name] = (parser || parseNumeric).call(this, isMulti ? props[key][isMulti] : props[key], id);
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ });
127
+ }
128
+ var parseNumeric = (property, id) => parseInt(typeof property === "object" ? property[id] : property);
129
+ var parseDate = (property, id) => new Date(Date.parse(typeof property === "object" ? property[id] : property));
130
+ var addClass = (n, str) => n && str.split(" ").every((s) => s && L.DomUtil.addClass(n, s));
131
+ var removeClass = (n, str) => n && str.split(" ").every((s) => s && L.DomUtil.removeClass(n, s));
132
+ var toggleClass = (n, str, cond) => (cond ? addClass : removeClass)(n, str);
133
+ var replaceClass = (n, rem, add) => rem && removeClass(n, rem) || add && addClass(n, add);
134
+ var style = (n, k, v) => typeof v === "undefined" && L.DomUtil.getStyle(n, k) || n.style.setProperty(k, v);
135
+ var toggleStyle = (n, k, v, cond) => style(n, k, cond ? v : "");
136
+ var setAttributes = (n, attrs) => {
137
+ for (let k in attrs) {
138
+ n.setAttribute(k, attrs[k]);
139
+ }
140
+ };
141
+ var toggleEvent = (el, e, fn, cond) => el[cond ? "on" : "off"](e, fn);
142
+ var create = (tag, str, attrs, n) => {
143
+ let elem = L.DomUtil.create(tag, str || "");
144
+ if (attrs) setAttributes(elem, attrs);
145
+ if (n) append(n, elem);
146
+ return elem;
147
+ };
148
+ var append = (n, c) => n.appendChild(c);
149
+ var insert = (n, c, pos) => n.insertAdjacentElement(pos, c);
150
+ var select = (str, n) => (n || document).querySelector(str);
151
+ var each = (obj, fn) => {
152
+ for (let i in obj) fn(obj[i], i);
153
+ };
154
+ var randomId = () => Math.random().toString(36).substr(2, 9);
155
+ var iMax = (iVal, max = -Infinity) => iVal > max ? iVal : max;
156
+ var iMin = (iVal, min = Infinity) => iVal < min ? iVal : min;
157
+ var iAvg = (iVal, avg = 0, idx = 1) => (iVal + avg * (idx - 1)) / idx;
158
+ var iSum = (iVal, sum = 0) => iVal + sum;
159
+ var { on, off } = L.DomEvent;
160
+ var { throttle, wrapNum } = L.Util;
161
+ var { hasClass } = L.DomUtil;
162
+ var round = L.Util.formatNum;
163
+ var clamp = (val, range) => range ? val < range[0] ? range[0] : val > range[1] ? range[1] : val : val;
164
+ var wrapDelta = (curr, prev, deltaMax) => Math.abs(curr - prev) > deltaMax ? prev + deltaMax * Math.sign(curr - prev) : curr;
165
+ function cloneDeep(o, skipProps = [], cache = []) {
166
+ switch (!o || typeof o) {
167
+ case "object":
168
+ const hit = cache.filter((c) => o === c.original)[0];
169
+ if (hit) return hit.copy;
170
+ const copy = Array.isArray(o) ? [] : Object.create(Object.getPrototypeOf(o));
171
+ cache.push({ original: o, copy });
172
+ Object.getOwnPropertyNames(o).forEach(function(prop) {
173
+ const propdesc = Object.getOwnPropertyDescriptor(o, prop);
174
+ Object.defineProperty(
175
+ copy,
176
+ prop,
177
+ propdesc.get || propdesc.set ? propdesc : {
178
+ // deep copy data properties
179
+ writable: propdesc.writable,
180
+ configurable: propdesc.configurable,
181
+ enumerable: propdesc.enumerable,
182
+ value: skipProps.includes(prop) ? propdesc.value : cloneDeep(propdesc.value, skipProps, cache)
183
+ }
184
+ );
185
+ });
186
+ return copy;
187
+ case "function":
188
+ case "symbol":
189
+ console.warn("cloneDeep: " + typeof o + "s not fully supported:", o);
190
+ case true:
191
+ // null, undefined or falsy primitive
192
+ default:
193
+ return o;
194
+ }
195
+ }
196
+
197
+ // src/options.js
198
+ var Options = {
199
+ autofitBounds: true,
200
+ autohide: false,
201
+ autohideMarker: true,
202
+ almostover: true,
203
+ altitude: true,
204
+ closeBtn: true,
205
+ collapsed: false,
206
+ detached: true,
207
+ distance: true,
208
+ distanceMarkers: { lazy: true, distance: true, direction: true },
209
+ dragging: !L.Browser.mobile,
210
+ downloadLink: "link",
211
+ elevationDiv: "#elevation-div",
212
+ edgeScale: { bar: true, icon: false, coords: false },
213
+ followMarker: true,
214
+ imperial: false,
215
+ legend: true,
216
+ handlers: ["Distance", "Time", "Altitude", "Slope", "Speed", "Acceleration"],
217
+ hotline: "elevation",
218
+ marker: "elevation-line",
219
+ markerIcon: L.divIcon({
220
+ className: "elevation-position-marker",
221
+ html: '<i class="elevation-position-icon"></i>',
222
+ iconSize: [32, 32],
223
+ iconAnchor: [16, 16]
224
+ }),
225
+ position: "topright",
226
+ polyline: {
227
+ className: "elevation-polyline",
228
+ color: "#000",
229
+ opacity: 0.75,
230
+ weight: 5,
231
+ lineCap: "round"
232
+ },
233
+ polylineSegments: {
234
+ className: "elevation-polyline-segments",
235
+ color: "#F00",
236
+ interactive: false
237
+ },
238
+ preferCanvas: false,
239
+ reverseCoords: false,
240
+ ruler: true,
241
+ theme: "lightblue-theme",
242
+ summary: "inline",
243
+ slope: false,
244
+ speed: false,
245
+ time: true,
246
+ timeFactor: 3600,
247
+ timestamps: false,
248
+ trkStart: { className: "start-marker", radius: 6, weight: 2, color: "#fff", fillColor: "#00d800", fillOpacity: 1, interactive: false },
249
+ trkEnd: { className: "end-marker", radius: 6, weight: 2, color: "#fff", fillColor: "#ff0606", fillOpacity: 1, interactive: false },
250
+ waypoints: true,
251
+ wptIcons: {
252
+ "": L.divIcon({
253
+ className: "elevation-waypoint-marker",
254
+ html: '<i class="elevation-waypoint-icon default"></i>',
255
+ iconSize: [30, 30],
256
+ iconAnchor: [8, 30]
257
+ })
258
+ },
259
+ wptLabels: true,
260
+ xAttr: "dist",
261
+ xLabel: "km",
262
+ yAttr: "z",
263
+ yLabel: "m",
264
+ zFollow: false,
265
+ zooming: !L.Browser.Mobile,
266
+ // Quite uncommon and undocumented options
267
+ margins: { top: 30, right: 30, bottom: 30, left: 40 },
268
+ height: screen.height * 0.3 || 200,
269
+ width: screen.width * 0.6 || 600,
270
+ xTicks: void 0,
271
+ yTicks: void 0,
272
+ decimalsX: 2,
273
+ decimalsY: 0,
274
+ forceAxisBounds: false,
275
+ interpolation: "curveLinear",
276
+ yAxisMax: void 0,
277
+ yAxisMin: void 0,
278
+ // Prevent CORS issues for relative locations (dynamic import)
279
+ srcFolder: (document.currentScript && document.currentScript.src || null || document.baseURI).split("/").slice(0, -1).join("/") + "/"
280
+ };
281
+
282
+ // src/control.js
283
+ if (!L._ || !L.i18n) {
284
+ L._ = L.i18n = (string, data) => string;
285
+ }
286
+ var Elevation = L.Control.Elevation = L.Control.extend({
287
+ includes: L.Evented ? L.Evented.prototype : L.Mixin.Events,
288
+ options: Options,
289
+ __mileFactor: 0.621371,
290
+ // 1 km = (0.621371 mi)
291
+ __footFactor: 3.28084,
292
+ // 1 m = (3.28084 ft)
293
+ __D3: "https://unpkg.com/d3@7.8.4/dist/d3.min.js",
294
+ __TOGEOJSON: "https://unpkg.com/@tmcw/togeojson@5.6.2/dist/togeojson.umd.js",
295
+ __LGEOMUTIL: "https://unpkg.com/leaflet-geometryutil@0.10.1/src/leaflet.geometryutil.js",
296
+ __LALMOSTOVER: "https://unpkg.com/leaflet-almostover@1.0.1/src/leaflet.almostover.js",
297
+ __LHOTLINE: "../libs/leaflet-hotline.min.js",
298
+ __LDISTANCEM: "../libs/leaflet-distance-marker.min.js",
299
+ __LEDGESCALE: "../libs/leaflet-edgescale.min.js",
300
+ __LCHART: "../src/components/chart.js",
301
+ __LMARKER: "../src/components/marker.js",
302
+ __LSUMMARY: "../src/components/summary.js",
303
+ __modulesFolder: "../src/handlers/",
304
+ __btnIcon: "../images/elevation.svg",
305
+ /*
306
+ * Add data to the diagram either from GPX or GeoJSON and update the axis domain and data
307
+ */
308
+ addData(d, layer) {
309
+ this.import(this.__D3).then(() => {
310
+ if (this._modulesLoaded) {
311
+ layer = layer ?? (d.on && d);
312
+ this._addData(d);
313
+ this._addLayer(layer);
314
+ this._fireEvt("eledata_added", { data: d, layer, track_info: this.track_info });
315
+ } else {
316
+ this.once("modules_loaded", () => this.addData(d, layer));
317
+ }
318
+ });
319
+ },
320
+ /**
321
+ * Adds the control to the given map.
322
+ */
323
+ addTo(map) {
324
+ if (this.options.detached) {
325
+ let parent = select(this.options.elevationDiv);
326
+ let eleDiv = this.onAdd(map);
327
+ parent ? append(parent, eleDiv) : insert(map.getContainer(), eleDiv, "afterend");
328
+ } else {
329
+ L.Control.prototype.addTo.call(this, map);
330
+ }
331
+ return this;
332
+ },
333
+ /*
334
+ * Reset data and display
335
+ */
336
+ clear() {
337
+ if (this._marker) this._marker.remove();
338
+ if (this._chart) this._clearChart();
339
+ if (this._layers) this._clearLayers(this._layers);
340
+ if (this._markers) this._clearLayers(this._markers);
341
+ if (this._circleMarkers) this._circleMarkers.remove();
342
+ if (this._hotline) this._hotline.eachLayer((l) => l.options.renderer.remove());
343
+ if (this._hotline) this._clearLayers(this._hotline);
344
+ this._data = [];
345
+ this.track_info = {};
346
+ this._yCoordMin = 0;
347
+ this._yCoordMax = -Infinity;
348
+ this._fireEvt("eledata_clear");
349
+ this._updateChart();
350
+ },
351
+ _clearChart() {
352
+ if (this._events && this._events.elechart_updated) {
353
+ this._events.elechart_updated.forEach(({ fn, ctx }) => this.off("elechart_updated", fn, ctx));
354
+ }
355
+ if (this._chart && this._chart._container) {
356
+ this._chart._container.selectAll("g.point .point").remove();
357
+ this._chart.clear();
358
+ }
359
+ },
360
+ _clearLayers(l) {
361
+ l = l || this._layers;
362
+ if (l && l.eachLayer) {
363
+ l.eachLayer((f) => f.remove());
364
+ l.clearLayers();
365
+ }
366
+ },
367
+ /**
368
+ * TODO: Create a base class to handle custom data attributes (heart rate, cadence, temperature, ...)
369
+ *
370
+ * @link https://leafletjs.com/examples/extending/extending-3-controls.html#handlers
371
+ */
372
+ // addHandler: function (name, HandlerClass) {
373
+ // if (HandlerClass) {
374
+ // let handler = this[name] = new HandlerClass(this);
375
+ // this.handlers.push(handler);
376
+ // if (this.options[name]) {
377
+ // handler.enable();
378
+ // }
379
+ // }
380
+ // return this;
381
+ // },
382
+ /**
383
+ * Disable chart brushing.
384
+ */
385
+ disableBrush() {
386
+ this._chart._brushEnabled = false;
387
+ this._resetDrag();
388
+ },
389
+ /**
390
+ * Enable chart brushing.
391
+ */
392
+ enableBrush() {
393
+ this._chart._brushEnabled = true;
394
+ },
395
+ /**
396
+ * Disable chart zooming.
397
+ */
398
+ disableZoom() {
399
+ this._chart._zoomEnabled = false;
400
+ this._chart._resetZoom();
401
+ },
402
+ /**
403
+ * Enable chart zooming.
404
+ */
405
+ enableZoom() {
406
+ this._chart._zoomEnabled = true;
407
+ },
408
+ /**
409
+ * Sets a map view that contains the given geographical bounds.
410
+ */
411
+ fitBounds(bounds) {
412
+ bounds = bounds || this.getBounds();
413
+ if (this._map && bounds.isValid()) this._map.fitBounds(bounds);
414
+ },
415
+ getBounds(data) {
416
+ return L.latLngBounds((data || this._data).map((d) => d.latlng));
417
+ },
418
+ /**
419
+ * Get default zoom level (followMarker: true).
420
+ */
421
+ getZFollow() {
422
+ return this.options.zFollow;
423
+ },
424
+ /**
425
+ * Hide current elevation chart profile.
426
+ */
427
+ hide() {
428
+ style(this._container, "display", "none");
429
+ },
430
+ /**
431
+ * Initialize chart control "options" and "container".
432
+ */
433
+ initialize(opts) {
434
+ opts = L.setOptions(this, L.extend({}, cloneDeep(Options), opts));
435
+ this._data = [];
436
+ this._layers = L.featureGroup();
437
+ this._markers = L.featureGroup();
438
+ this._hotline = L.featureGroup();
439
+ this._circleMarkers = L.featureGroup();
440
+ this._markedSegments = L.polyline([]);
441
+ this._start = L.circleMarker([0, 0], opts.trkStart || Options.trkStart);
442
+ this._end = L.circleMarker([0, 0], opts.trkEnd || Options.trkEnd);
443
+ this._chartEnabled = true;
444
+ this._yCoordMin = 0;
445
+ this._yCoordMax = -Infinity;
446
+ this.track_info = {};
447
+ if (opts.followMarker) this._setMapView = throttle(this._setMapView, 300, this);
448
+ if (opts.legend) opts.margins.bottom += 30;
449
+ if (opts.theme) opts.polylineSegments.className += " " + opts.theme;
450
+ if (opts.wptIcons === true) opts.wptIcons = Options.wptIcons;
451
+ if (opts.distanceMarkers === true) opts.distanceMarkers = Options.distanceMarkers;
452
+ if (opts.trkStart) this._start.addTo(this._circleMarkers);
453
+ if (opts.trkEnd) this._end.addTo(this._circleMarkers);
454
+ this._markedSegments.setStyle(opts.polylineSegments);
455
+ L.extend(Colors, opts.colors || {});
456
+ this._fixCanvasPaths();
457
+ this._fixTooltipSize();
458
+ },
459
+ /**
460
+ * Javascript scripts downloader (lazy loader)
461
+ */
462
+ import(src, condition) {
463
+ if (Array.isArray(src)) {
464
+ return Promise.all(src.map((m) => this.import(m)));
465
+ }
466
+ switch (src) {
467
+ case this.__D3:
468
+ condition = typeof d3 !== "object";
469
+ break;
470
+ case this.__TOGEOJSON:
471
+ condition = typeof toGeoJSON !== "object";
472
+ break;
473
+ case this.__LGEOMUTIL:
474
+ condition = typeof L.GeometryUtil !== "object";
475
+ break;
476
+ case this.__LALMOSTOVER:
477
+ condition = typeof L.Handler.AlmostOver !== "function";
478
+ break;
479
+ case this.__LDISTANCEM:
480
+ condition = typeof L.DistanceMarkers !== "function";
481
+ break;
482
+ case this.__LEDGESCALE:
483
+ condition = typeof L.Control.EdgeScale !== "function";
484
+ break;
485
+ case this.__LHOTLINE:
486
+ condition = typeof L.Hotline !== "function";
487
+ break;
488
+ }
489
+ return condition !== false ? import(resolveURL(src, this.options.srcFolder)) : Promise.resolve();
490
+ },
491
+ /**
492
+ * Load elevation data (GPX, GeoJSON, KML or TCX).
493
+ */
494
+ load(data) {
495
+ this._parseFromString(data).then((geojson) => geojson ? this._loadLayer(geojson) : this._loadFile(data));
496
+ },
497
+ /**
498
+ * Create container DOM element and related event listeners.
499
+ * Called on control.addTo(map).
500
+ */
501
+ onAdd(map) {
502
+ this._map = map;
503
+ let container = this._container = create("div", "elevation-control " + this.options.theme + " " + (this.options.detached ? "elevation-detached" : "leaflet-control"), this.options.detached ? { id: "elevation-" + randomId() } : {});
504
+ if (!this.eleDiv) this.eleDiv = container;
505
+ this._loadModules(this.options.handlers).then(() => {
506
+ this._initChart(container);
507
+ this._initButton(container);
508
+ this._initSummary(container);
509
+ this._initMarker(map);
510
+ this._initLayer(map);
511
+ this._modulesLoaded = true;
512
+ this.fire("modules_loaded");
513
+ });
514
+ this.fire("add");
515
+ return container;
516
+ },
517
+ /**
518
+ * Clean up control code and related event listeners.
519
+ * Called on control.remove().
520
+ */
521
+ onRemove(map) {
522
+ this._container = null;
523
+ map.off("zoom viewreset zoomanim", this._hideMarker, this).off("resize", this._resetView, this).off("resize", this._resizeChart, this).off("mousedown", this._resetDrag, this);
524
+ off(map.getContainer(), "mousewheel", this._resetDrag, this);
525
+ off(map.getContainer(), "touchstart", this._resetDrag, this);
526
+ off(document, "keydown", this._onKeyDown, this);
527
+ this.off("eledata_added eledata_loaded", this._updateChart, this).off("eledata_added eledata_loaded", this._updateSummary, this);
528
+ this.fire("remove");
529
+ },
530
+ /**
531
+ * Redraws the chart control. Sometimes useful after screen resize.
532
+ */
533
+ redraw() {
534
+ this._resizeChart();
535
+ },
536
+ /**
537
+ * Set default zoom level (followMarker: true).
538
+ */
539
+ setZFollow(zoom) {
540
+ this.options.zFollow = zoom;
541
+ },
542
+ /**
543
+ * Hide current elevation chart profile.
544
+ */
545
+ show() {
546
+ style(this._container, "display", "block");
547
+ },
548
+ /*
549
+ * Parsing data either from GPX or GeoJSON and update the diagram data
550
+ */
551
+ _addData(d) {
552
+ if (!d) {
553
+ return;
554
+ }
555
+ if (d.type === "FeatureCollection") {
556
+ return each(d.features, (feature) => this._addData(feature));
557
+ } else if (d.type === "Feature") {
558
+ let geom = d.geometry;
559
+ if (geom) {
560
+ switch (geom.type) {
561
+ case "LineString":
562
+ return this._addGeoJSONData(geom.coordinates, d.properties);
563
+ case "MultiLineString":
564
+ return each(geom.coordinates, (coords, i) => this._addGeoJSONData(coords, d.properties, i));
565
+ case "Point":
566
+ default:
567
+ return console.warn("Unsopperted GeoJSON feature geometry type:" + geom.type);
568
+ }
569
+ }
570
+ }
571
+ if (d._latlngs) {
572
+ return this._addGeoJSONData(d._latlngs, d.feature && d.feature.properties);
573
+ }
574
+ },
575
+ /*
576
+ * Parsing of GeoJSON data lines and their elevation in z-coordinate
577
+ */
578
+ _addGeoJSONData(coords, properties, nestingLevel) {
579
+ let props = properties && properties.coordinateProperties || properties;
580
+ coords.forEach((point, i) => {
581
+ point.meta = point.meta ?? { time: null, ele: null };
582
+ point.prev = (attr) => attr ? this._data[i > 0 ? i - 1 : 0][attr] : this._data[i > 0 ? i - 1 : 0];
583
+ this.fire("elepoint_init", { point, props, id: i, isMulti: nestingLevel });
584
+ this._addPoint(
585
+ point.lat ?? point[1],
586
+ point.lng ?? point[0],
587
+ point.alt ?? point.meta.ele ?? point[2]
588
+ );
589
+ this.fire("elepoint_added", { point, index: this._data.length - 1 });
590
+ if (this._yCoordMin > this._data[this._data.length - 1][this.options.yAttr]) this._yCoordMin = this._data[this._data.length - 1][this.options.yAttr];
591
+ if (this._yCoordMax < this._data[this._data.length - 1][this.options.yAttr]) this._yCoordMax = this._data[this._data.length - 1][this.options.yAttr];
592
+ });
593
+ this.fire("eletrack_added", { coords, index: this._data.length - 1 });
594
+ },
595
+ /*
596
+ * Parse and push a single (x, y, z) point to current elevation profile.
597
+ */
598
+ _addPoint(x, y, z) {
599
+ if (this.options.reverseCoords) {
600
+ [x, y] = [y, x];
601
+ }
602
+ this._data.push({
603
+ x,
604
+ y,
605
+ z,
606
+ latlng: L.latLng(x, y, z)
607
+ });
608
+ this.fire("eledata_updated", { index: this._data.length - 1 });
609
+ },
610
+ _addLayer(layer) {
611
+ if (layer) this._layers.addLayer(layer);
612
+ if (layer && this.options.distanceMarkers && this.options.distanceMarkers.lazy) {
613
+ layer.on("add remove", ({ target, type }) => L.DistanceMarkers && target instanceof L.Polyline && target[type + "DistanceMarkers"]());
614
+ }
615
+ return layer;
616
+ },
617
+ _addMarker(marker) {
618
+ if (marker) this._markers.addLayer(marker);
619
+ return marker;
620
+ },
621
+ /**
622
+ * Initialize "L.AlmostOver" integration
623
+ */
624
+ _initAlmostOverHandler(map, layer) {
625
+ return map && this.options.almostOver && !L.Browser.mobile ? this.import([this.__LGEOMUTIL, this.__LALMOSTOVER]).then(() => {
626
+ map.addHandler("almostOver", L.Handler.AlmostOver);
627
+ if (L.GeometryUtil && map.almostOver && map.almostOver.enabled()) {
628
+ map.almostOver.addLayer(layer);
629
+ map.on("almost:move", this._onMouseMoveLayer, this).on("almost:out", this._onMouseOut, this);
630
+ this.once("eledata_clear", () => {
631
+ map.almostOver.removeLayer(layer);
632
+ map.off("almost:move", this._onMouseMoveLayer, this).off("almost:out", this._onMouseOut, this);
633
+ });
634
+ }
635
+ }) : Promise.resolve();
636
+ },
637
+ /**
638
+ * Initialize "L.DistanceMarkers" integration
639
+ */
640
+ _initDistanceMarkers() {
641
+ return this.options.distanceMarkers ? this.import([this.__LGEOMUTIL, this.__LDISTANCEM]) : Promise.resolve();
642
+ },
643
+ /**
644
+ * Initialize "L.Control.EdgeScale" integration
645
+ */
646
+ _initEdgeScale(map) {
647
+ return this.options.edgeScale ? this.import(this.__LEDGESCALE).then(() => {
648
+ map.edgeScaleControl = map.edgeScaleControl || L.control.edgeScale("boolean" !== typeof this.options.edgeScale ? this.options.edgeScale : {}).addTo(map);
649
+ }) : Promise.resolve();
650
+ },
651
+ _initHotLine(layer) {
652
+ let prop = typeof this.options.hotline == "string" ? this.options.hotline : "elevation";
653
+ return this.options.hotline ? this.import(this.__LHOTLINE).then(() => {
654
+ layer.eachLayer((trkseg) => {
655
+ if (trkseg.feature.geometry.type != "Point") {
656
+ let geo = L.geoJson(trkseg.toGeoJSON(), { coordsToLatLng: (coords) => L.latLng(coords[0], coords[1], coords[2] * (this.options.altitudeFactor || 1)) });
657
+ let line = L.hotline(geo.toGeoJSON().features[0].geometry.coordinates, {
658
+ renderer: L.Hotline.renderer(),
659
+ min: isFinite(this.track_info[prop + "_min"]) ? this.track_info[prop + "_min"] : 0,
660
+ max: isFinite(this.track_info[prop + "_max"]) ? this.track_info[prop + "_max"] : 1,
661
+ palette: {
662
+ 0: "#008800",
663
+ 0.5: "#ffff00",
664
+ 1: "#ff0000"
665
+ },
666
+ weight: 5,
667
+ outlineColor: "#000000",
668
+ outlineWidth: 1
669
+ }).addTo(this._hotline);
670
+ let alpha = trkseg.options.style && trkseg.options.style.opacity || 1;
671
+ trkseg.on("add remove", ({ type }) => {
672
+ trkseg.setStyle({ opacity: type == "add" ? 0 : alpha });
673
+ line[type == "add" ? "addTo" : "removeFrom"](trkseg._map);
674
+ if (line._renderer) line._renderer._container.parentElement.insertBefore(line._renderer._container, line._renderer._container.parentElement.firstChild);
675
+ });
676
+ }
677
+ });
678
+ }) : Promise.resolve();
679
+ },
680
+ /**
681
+ * Initialize "L.AlmostOver" and "L.DistanceMarkers"
682
+ */
683
+ _initMapIntegrations(layer) {
684
+ let map = this._map;
685
+ if (map) {
686
+ if (this._data.length) {
687
+ this._start.setLatLng(this._data[0].latlng);
688
+ this._end.setLatLng(this._data[this._data.length - 1].latlng);
689
+ }
690
+ Promise.all([
691
+ this._initHotLine(layer),
692
+ this._initAlmostOverHandler(map, layer),
693
+ this._initDistanceMarkers(),
694
+ this._initEdgeScale(map)
695
+ ]).then(() => {
696
+ if (this.options.polyline) {
697
+ this._layers.addLayer(layer.addTo(map));
698
+ this._circleMarkers.addTo(map);
699
+ }
700
+ if (this.options.autofitBounds) {
701
+ this.fitBounds(layer.getBounds());
702
+ }
703
+ map.invalidateSize();
704
+ });
705
+ } else {
706
+ this.once("add", () => this._initMapIntegrations(layer));
707
+ }
708
+ },
709
+ /*
710
+ * Collapse current chart control.
711
+ */
712
+ _collapse() {
713
+ replaceClass(this._container, "elevation-expanded", "elevation-collapsed");
714
+ if (this._map) this._map.invalidateSize();
715
+ },
716
+ /*
717
+ * Expand current chart control.
718
+ */
719
+ _expand() {
720
+ replaceClass(this._container, "elevation-collapsed", "elevation-expanded");
721
+ if (this._map) this._map.invalidateSize();
722
+ },
723
+ /**
724
+ * Add some basic colors to leaflet canvas renderer (preferCanvas: true).
725
+ */
726
+ _fixCanvasPaths() {
727
+ let oldProto = L.Canvas.prototype._fillStroke;
728
+ let control = this;
729
+ let theme = this.options.theme.split(" ")[0].replace("-theme", "");
730
+ let color = Colors[theme] || {};
731
+ L.Canvas.include({
732
+ _fillStroke(ctx, layer) {
733
+ if (control._layers.hasLayer(layer)) {
734
+ let options = layer.options;
735
+ options.color = color.line || color.area || theme;
736
+ options.stroke = !!options.color;
737
+ oldProto.call(this, ctx, layer);
738
+ if (options.stroke && options.weight !== 0) {
739
+ let oldVal = ctx.globalCompositeOperation || "source-over";
740
+ ctx.globalCompositeOperation = "destination-over";
741
+ ctx.strokeStyle = color.outline || "#FFF";
742
+ ctx.lineWidth = options.weight * 1.75;
743
+ ctx.stroke();
744
+ ctx.globalCompositeOperation = oldVal;
745
+ }
746
+ } else {
747
+ oldProto.call(this, ctx, layer);
748
+ }
749
+ }
750
+ });
751
+ },
752
+ /**
753
+ * Partial fix for initial tooltip size
754
+ *
755
+ * @link https://github.com/Raruto/leaflet-elevation/issues/81#issuecomment-713477050
756
+ */
757
+ _fixTooltipSize() {
758
+ this.on(
759
+ "elechart_init",
760
+ () => this.once("elechart_change elechart_hover", ({ data, xCoord }) => {
761
+ if (this._chartEnabled) {
762
+ this._chart._showDiagramIndicator(data, xCoord);
763
+ this._chart._showDiagramIndicator(data, xCoord);
764
+ }
765
+ this._updateMarker(data);
766
+ })
767
+ );
768
+ },
769
+ /*
770
+ * Finds a data entry for the given LatLng
771
+ */
772
+ _findItemForLatLng(latlng) {
773
+ return this._data[this._chart._findIndexForLatLng(latlng)];
774
+ },
775
+ /*
776
+ * Finds a data entry for the given xDiagCoord
777
+ */
778
+ _findItemForX(x) {
779
+ return this._data[this._chart._findIndexForXCoord(x)];
780
+ },
781
+ /**
782
+ * Fires an event of the specified type.
783
+ */
784
+ _fireEvt(type, data, propagate) {
785
+ if (this.fire) this.fire(type, data, propagate);
786
+ if (this._map) this._map.fire(type, data, propagate);
787
+ },
788
+ /*
789
+ * Hides the position/height indicator marker drawn onto the map
790
+ */
791
+ _hideMarker() {
792
+ if (this.options.autohideMarker) {
793
+ this._marker.remove();
794
+ }
795
+ },
796
+ /**
797
+ * Generate "svg" chart (DOM element).
798
+ */
799
+ _initChart(container) {
800
+ let opts = this.options;
801
+ let map = this._map;
802
+ if (opts.detached) {
803
+ let { offsetWidth, offsetHeight } = this.eleDiv;
804
+ if (offsetWidth > 0) opts.width = offsetWidth;
805
+ if (offsetHeight > 20) opts.height = offsetHeight - 20;
806
+ } else {
807
+ let { clientWidth } = map.getContainer();
808
+ opts._maxWidth = opts._maxWidth > opts.width ? opts._maxWidth : opts.width;
809
+ this._container.style.maxWidth = opts._maxWidth + "px";
810
+ if (opts._maxWidth > clientWidth) opts.width = clientWidth - 30;
811
+ }
812
+ this.import([this.__D3, this.__LCHART]).then((m) => {
813
+ let chart = this._chart = new (m[1] || Elevation).Chart(opts, this);
814
+ this._x = this._chart._x;
815
+ this._y = this._chart._y;
816
+ d3.select(container).call(chart.render());
817
+ chart.on("reset_drag", this._hideMarker, this).on("mouse_enter", this._onMouseEnter, this).on("dragged", this._onDragEnd, this).on("mouse_move", this._onMouseMove, this).on("mouse_out", this._onMouseOut, this).on("ruler_filter", this._onRulerFilter, this).on("zoom", this._updateChart, this).on("elepath_toggle", this._onToggleChart, this).on("margins_updated", this._resizeChart, this);
818
+ this.fire("elechart_init");
819
+ map.on("zoom viewreset zoomanim", this._hideMarker, this).on("resize", this._resetView, this).on("resize", this._resizeChart, this).on("rotate", this._rotateMarker, this).on("mousedown", this._resetDrag, this);
820
+ on(map.getContainer(), "mousewheel", this._resetDrag, this);
821
+ on(map.getContainer(), "touchstart", this._resetDrag, this);
822
+ on(document, "keydown", this._onKeyDown, this);
823
+ this.on("eledata_added eledata_loaded", this._updateChart, this).on("eledata_added eledata_loaded", this._updateSummary, this);
824
+ this._updateChart();
825
+ this._updateSummary();
826
+ });
827
+ },
828
+ _initLayer() {
829
+ this._layers.on("layeradd layerremove", ({ layer, type }) => {
830
+ let node = layer.getElement && layer.getElement();
831
+ toggleClass(node, this.options.polyline.className + " " + this.options.theme, type == "layeradd");
832
+ toggleEvent(layer, "mousemove", this._onMouseMoveLayer.bind(this), type == "layeradd");
833
+ toggleEvent(layer, "mouseout", this._onMouseOut.bind(this), type == "layeradd");
834
+ });
835
+ },
836
+ _initMarker(map) {
837
+ let pane = map.getPane("elevationPane");
838
+ if (!pane) {
839
+ pane = this._pane = map.createPane("elevationPane", map.getPane("norotatePane") || map.getPane("mapPane"));
840
+ pane.style.zIndex = 625;
841
+ pane.style.pointerEvents = "none";
842
+ }
843
+ if (this._renderer) this._renderer.remove();
844
+ this._renderer = L.svg({ pane: "elevationPane" }).addTo(this._map);
845
+ this.import([this.__D3, this.__LMARKER]).then((m) => {
846
+ this._marker = new (m[1] || Elevation).Marker(this.options, this);
847
+ this.fire("elechart_marker");
848
+ });
849
+ },
850
+ /**
851
+ * Inspired by L.Control.Layers
852
+ */
853
+ _initButton(container) {
854
+ L.DomEvent.disableClickPropagation(container).disableScrollPropagation(container);
855
+ this.options.collapsed ? this._collapse() : this._expand();
856
+ if (this.options.autohide) {
857
+ on(container, "mouseover", this._expand, this);
858
+ on(container, "mouseout", this._collapse, this);
859
+ this._map.on("click", this._collapse, this);
860
+ }
861
+ if (this.options.closeBtn) {
862
+ let link = this._button = create("a", "elevation-toggle-icon", { href: "#", title: L._("Elevation") }, container);
863
+ on(link, "click", L.DomEvent.stop);
864
+ on(link, "click", this._toggle, this);
865
+ on(link, "focus", this._toggle, this);
866
+ fetch(resolveURL(this.__btnIcon, this.options.srcFolder)).then((r) => r.ok && r.text().then((img) => link.innerHTML = img));
867
+ }
868
+ },
869
+ _initSummary(container) {
870
+ this.import(this.__LSUMMARY).then((m) => {
871
+ this._summary = new (m || Elevation).Summary({ summary: this.options.summary }, this);
872
+ this.on("elechart_init", () => {
873
+ d3.select(container).call(this._summary.render());
874
+ });
875
+ });
876
+ },
877
+ /**
878
+ * Retrieve data from a remote url (HTTP).
879
+ */
880
+ _loadFile(url) {
881
+ fetch(url).then((response) => response.text()).then((data) => {
882
+ this._downloadURL = url;
883
+ this._parseFromString(data).then((geojson) => geojson && this._loadLayer(geojson));
884
+ }).catch((err) => console.warn(err));
885
+ },
886
+ /**
887
+ * Dynamically import only required javascript modules (code splitting)
888
+ */
889
+ _loadModules(handlers) {
890
+ handlers = handlers.map((h) => typeof h === "string" && typeof Elevation[h] !== "undefined" ? Elevation[h] : h);
891
+ let modules = handlers.map((file) => typeof file === "string" && this.import(this.__modulesFolder + file.toLowerCase() + ".js") || file instanceof Promise && file || Promise.resolve());
892
+ return Promise.all(modules).then((m) => {
893
+ each(m, (exported, i) => {
894
+ let fn = exported && Object.keys(exported)[0];
895
+ if (fn) {
896
+ handlers[i] = Elevation[fn] = Elevation[fn] ?? exported[fn];
897
+ }
898
+ });
899
+ each(handlers, (h) => ["function", "object"].includes(typeof h) && this._registerHandler(h));
900
+ });
901
+ },
902
+ /**
903
+ * Simple GeoJSON data loader (L.GeoJSON).
904
+ */
905
+ _loadLayer(geojson) {
906
+ let { polyline, theme, waypoints, wptIcons, wptLabels, distanceMarkers } = this.options;
907
+ let style2 = L.extend({}, polyline);
908
+ if (theme) {
909
+ style2.className += " " + theme;
910
+ }
911
+ if (geojson.name) {
912
+ this.track_info.name = geojson.name;
913
+ }
914
+ let layer = L.geoJson(geojson, {
915
+ distanceMarkers,
916
+ style: style2,
917
+ pointToLayer: (feature, latlng) => {
918
+ if (waypoints) {
919
+ let { desc, name, sym } = feature.properties;
920
+ desc = desc || "";
921
+ name = name || "";
922
+ if ([true, "dots"].includes(waypoints)) {
923
+ this._registerCheckPoint({
924
+ latlng,
925
+ label: [true, "dots"].includes(wptLabels) ? name : ""
926
+ });
927
+ }
928
+ if ([true, "markers"].includes(waypoints) && wptIcons != false) {
929
+ return this._registerMarker({
930
+ latlng,
931
+ sym: (sym ?? name).replace(/["']/g, "").replace(/ /g, "-").toLowerCase(),
932
+ content: [true, "markers"].includes(wptLabels) && (name || desc) && decodeURI("<b>" + name + "</b>" + (desc.length > 0 ? "<br>" + desc : ""))
933
+ });
934
+ }
935
+ }
936
+ },
937
+ onEachFeature: (feature, layer2) => feature.geometry && feature.geometry.type != "Point" && this.addData(feature, layer2)
938
+ });
939
+ this.import(this.__D3).then(() => {
940
+ this._initMapIntegrations(layer);
941
+ const event_data = { data: geojson, layer, name: this.track_info.name, track_info: this.track_info };
942
+ if (this._modulesLoaded) {
943
+ this._fireEvt("eledata_loaded", event_data);
944
+ } else {
945
+ this.once("modules_loaded", () => this._fireEvt("eledata_loaded", event_data));
946
+ }
947
+ });
948
+ return layer;
949
+ },
950
+ _onDragEnd({ dragstart, dragend }) {
951
+ this._hideMarker();
952
+ this.fitBounds(L.latLngBounds([dragstart.latlng, dragend.latlng]));
953
+ this.fire("elechart_dragged");
954
+ },
955
+ _onKeyDown({ key }) {
956
+ if (!this.options.detached && key === "Escape") {
957
+ this._collapse();
958
+ }
959
+ ;
960
+ },
961
+ /**
962
+ * Trigger mouseenter event.
963
+ */
964
+ _onMouseEnter() {
965
+ this.fire("elechart_enter");
966
+ },
967
+ /*
968
+ * Handles the moueseover the chart and displays distance and altitude level.
969
+ */
970
+ _onMouseMove({ xCoord }) {
971
+ if (this._chartEnabled && this._data.length) {
972
+ let item = this._findItemForX(xCoord);
973
+ if (item) {
974
+ if (this._chartEnabled) this._chart._showDiagramIndicator(item, xCoord);
975
+ this._updateMarker(item);
976
+ this._setMapView(item);
977
+ if (this._map) {
978
+ addClass(this._map.getContainer(), "elechart-hover");
979
+ }
980
+ this.fire("elechart_change", { data: item, xCoord });
981
+ this.fire("elechart_hover", { data: item, xCoord });
982
+ }
983
+ }
984
+ },
985
+ /*
986
+ * Handles mouseover events of the data layers on the map.
987
+ */
988
+ _onMouseMoveLayer({ latlng }) {
989
+ if (this._data.length) {
990
+ let item = this._findItemForLatLng(latlng);
991
+ if (item) {
992
+ let xCoord = item.xDiagCoord;
993
+ if (this._chartEnabled) this._chart._showDiagramIndicator(item, xCoord);
994
+ this._updateMarker(item);
995
+ this.fire("elechart_change", { data: item, xCoord });
996
+ }
997
+ }
998
+ },
999
+ /*
1000
+ * Handles the moueseout over the chart.
1001
+ */
1002
+ _onMouseOut() {
1003
+ if (!this.options.detached) {
1004
+ this._hideMarker();
1005
+ this._chart._hideDiagramIndicator();
1006
+ }
1007
+ if (this._map) {
1008
+ removeClass(this._map.getContainer(), "elechart-hover");
1009
+ }
1010
+ this.fire("elechart_leave");
1011
+ },
1012
+ /**
1013
+ * Handles the drag event over the ruler filter.
1014
+ */
1015
+ _onRulerFilter({ coords }) {
1016
+ this._updateMapSegments(coords);
1017
+ },
1018
+ /**
1019
+ * Toggle chart data on legend click
1020
+ */
1021
+ _onToggleChart({ name, enabled }) {
1022
+ this._chartEnabled = this._chart._hasActiveLayers();
1023
+ this._layers.eachLayer((layer) => toggleClass(layer.getElement && layer.getElement(), this.options.polyline.className + " " + this.options.theme, this._chartEnabled));
1024
+ this.options[name] = !enabled && this.options[name] == "disabled" ? "enabled" : "disabled";
1025
+ if (!this._chartEnabled) {
1026
+ this._chart._hideDiagramIndicator();
1027
+ this._marker.remove();
1028
+ }
1029
+ },
1030
+ /**
1031
+ * Simple GeoJSON Parser
1032
+ */
1033
+ _parseFromGeoJSONString(data) {
1034
+ try {
1035
+ return JSON.parse(data);
1036
+ } catch (e) {
1037
+ }
1038
+ },
1039
+ /**
1040
+ * Attempt to parse raw response data (GeoJSON or XML > GeoJSON)
1041
+ */
1042
+ _parseFromString(data) {
1043
+ return new Promise(
1044
+ (resolve) => this.import(this.__TOGEOJSON).then(() => {
1045
+ let geojson;
1046
+ try {
1047
+ geojson = this._parseFromXMLString(data.trim());
1048
+ } catch (e) {
1049
+ geojson = this._parseFromGeoJSONString(data.toString());
1050
+ }
1051
+ if (geojson) {
1052
+ geojson.name = geojson.name || (this._downloadURL || "").split("/").pop().split("#")[0].split("?")[0];
1053
+ }
1054
+ resolve(geojson);
1055
+ })
1056
+ );
1057
+ },
1058
+ /**
1059
+ * Simple XML Parser (GPX, KML, TCX)
1060
+ */
1061
+ _parseFromXMLString(data) {
1062
+ if (data.indexOf("<") != 0) {
1063
+ throw "Invalid XML";
1064
+ }
1065
+ let xml = new DOMParser().parseFromString(data, "text/xml");
1066
+ let type = xml.documentElement.tagName.toLowerCase();
1067
+ let name = xml.getElementsByTagName("name");
1068
+ if (xml.getElementsByTagName("parsererror").length) {
1069
+ throw "Invalid XML";
1070
+ }
1071
+ if (!(type in toGeoJSON)) {
1072
+ type = xml.documentElement.tagName == "TrainingCenterDatabase" ? "tcx" : "gpx";
1073
+ }
1074
+ let geojson = toGeoJSON[type](xml);
1075
+ geojson.name = name.length > 0 ? (Array.from(name).find((tag) => tag.parentElement.tagName == "trk") ?? name[0]).textContent : "";
1076
+ return geojson;
1077
+ },
1078
+ /**
1079
+ * Add chart profile to diagram
1080
+ */
1081
+ _registerAreaPath(props) {
1082
+ this.on("elechart_init", () => this._chart._registerAreaPath(props));
1083
+ },
1084
+ /**
1085
+ * Add chart grid to diagram
1086
+ */
1087
+ _registerAxisGrid(props) {
1088
+ this.on("elechart_axis", () => this._chart._registerAxisGrid(props));
1089
+ },
1090
+ /**
1091
+ * Add chart axis to diagram
1092
+ */
1093
+ _registerAxisScale(props) {
1094
+ this.on("elechart_axis", () => this._chart._registerAxisScale(props));
1095
+ },
1096
+ /**
1097
+ * Add a point of interest over the diagram
1098
+ */
1099
+ _registerCheckPoint(props) {
1100
+ const cb = () => this._chart._registerCheckPoint(props);
1101
+ this.on("elechart_updated", cb).once("eledata_clear", () => this.off("elechart_updated", cb));
1102
+ },
1103
+ /**
1104
+ * Base handler for iterative track statistics (dist, time, z, slope, speed, acceleration, ...)
1105
+ */
1106
+ _registerDataAttribute(props) {
1107
+ if (props.coordPropsToMeta) {
1108
+ this.on("elepoint_init", (e) => props.coordPropsToMeta.call(this, e));
1109
+ }
1110
+ let i, curr, prev, attr = props.attr || props.name;
1111
+ let lastValid = {};
1112
+ this.on("elepoint_added", ({ index, point }) => {
1113
+ i = index;
1114
+ prev = curr ?? this._data[i];
1115
+ curr = this._data[i];
1116
+ curr[attr] = props.pointToAttr.call(this, point, i);
1117
+ if (i > 0 && isNaN(prev[attr])) {
1118
+ if (!isNaN(lastValid[attr]) && !isNaN(curr[attr])) {
1119
+ prev[attr] = (lastValid[attr] + curr[attr]) / 2;
1120
+ } else if (!isNaN(lastValid[attr])) {
1121
+ prev[attr] = lastValid[attr];
1122
+ } else if (!isNaN(curr[attr])) {
1123
+ prev[attr] = curr[attr];
1124
+ }
1125
+ if (props.meta) {
1126
+ prev[props.meta] = prev[attr];
1127
+ }
1128
+ }
1129
+ if (isNaN(curr[attr])) {
1130
+ return;
1131
+ }
1132
+ lastValid[attr] = curr[attr];
1133
+ if (props.deltaMax) {
1134
+ curr[attr] = wrapDelta(curr[attr], prev[attr], props.deltaMax);
1135
+ }
1136
+ if (props.clampRange) {
1137
+ curr[attr] = clamp(curr[attr], props.clampRange);
1138
+ }
1139
+ if (!isNaN(props.decimals)) {
1140
+ curr[attr] = round(curr[attr], props.decimals);
1141
+ }
1142
+ if (props.stats) {
1143
+ for (const key in props.stats) {
1144
+ let sname = (props.statsName || attr) + (key != "" ? "_" : "");
1145
+ this.track_info[sname + key] = props.stats[key].call(this, curr[attr], this.track_info[sname + key], this._data.length);
1146
+ }
1147
+ }
1148
+ if (props.onPointAdded) props.onPointAdded.call(this, curr[attr], i, point);
1149
+ });
1150
+ },
1151
+ /**
1152
+ * Parse a module definition and attach related function listeners
1153
+ */
1154
+ _registerHandler(props) {
1155
+ if (typeof props === "function") {
1156
+ return this._registerHandler(props.call(this));
1157
+ }
1158
+ let {
1159
+ name,
1160
+ attr,
1161
+ required,
1162
+ deltaMax,
1163
+ clampRange,
1164
+ decimals,
1165
+ meta,
1166
+ unit,
1167
+ coordinateProperties,
1168
+ coordPropsToMeta: coordPropsToMeta2,
1169
+ pointToAttr,
1170
+ onPointAdded,
1171
+ stats,
1172
+ statsName,
1173
+ grid,
1174
+ scale,
1175
+ path,
1176
+ tooltip,
1177
+ summary
1178
+ } = props;
1179
+ if (this.options[name] || required) {
1180
+ this._registerDataAttribute({
1181
+ name,
1182
+ attr,
1183
+ meta,
1184
+ deltaMax,
1185
+ clampRange,
1186
+ decimals,
1187
+ coordPropsToMeta: coordPropsToMeta(coordinateProperties, meta || name, coordPropsToMeta2),
1188
+ pointToAttr,
1189
+ onPointAdded,
1190
+ stats,
1191
+ statsName
1192
+ });
1193
+ if (grid) {
1194
+ this._registerAxisGrid(L.extend({ name }, grid));
1195
+ }
1196
+ if (this.options[name] !== "summary") {
1197
+ if (scale) this._registerAxisScale(L.extend({ name, label: unit }, scale));
1198
+ if (path) this._registerAreaPath(L.extend({ name }, path));
1199
+ }
1200
+ if (tooltip || props.tooltips) {
1201
+ each([tooltip, ...props.tooltips || []], (t) => t && this._registerTooltip(L.extend({ name }, t)));
1202
+ }
1203
+ if (summary) {
1204
+ each(summary, (s, k) => summary[k] = L.extend({ unit }, s));
1205
+ this._registerSummary(summary);
1206
+ }
1207
+ }
1208
+ },
1209
+ _registerMarker({ latlng, sym, content }) {
1210
+ let { wptIcons } = this.options;
1211
+ if (!wptIcons.hasOwnProperty(sym)) {
1212
+ wptIcons[sym] = L.divIcon(L.extend({}, wptIcons[""].options, { html: '<i class="elevation-waypoint-icon ' + sym + '"></i>' }));
1213
+ }
1214
+ let marker = L.marker(latlng, { icon: wptIcons[sym] });
1215
+ if (content) {
1216
+ marker.bindPopup(content, { className: "elevation-popup", keepInView: true }).openPopup();
1217
+ marker.bindTooltip(content, { className: "elevation-tooltip", direction: "auto", sticky: true, opacity: 1 }).openTooltip();
1218
+ }
1219
+ return this._addMarker(marker);
1220
+ },
1221
+ /**
1222
+ * Add chart or marker tooltip info
1223
+ */
1224
+ _registerTooltip(props) {
1225
+ props.chart && this.on("elechart_init", () => this._chart._registerTooltip(L.extend({}, props, { value: props.chart })));
1226
+ props.marker && this.on("elechart_marker", () => this._marker._registerTooltip(L.extend({}, props, { value: props.marker })));
1227
+ },
1228
+ /**
1229
+ * Add summary info to diagram
1230
+ */
1231
+ _registerSummary(props) {
1232
+ this.on("elechart_summary", () => this._summary._registerSummary(props));
1233
+ },
1234
+ /*
1235
+ * Removes the drag rectangle and zoms back to the total extent of the data.
1236
+ */
1237
+ _resetDrag() {
1238
+ this._chart._resetDrag();
1239
+ this._hideMarker();
1240
+ },
1241
+ /**
1242
+ * Resets drag, marker and bounds.
1243
+ */
1244
+ _resetView() {
1245
+ if (this._map && this._map._isFullscreen) return;
1246
+ this._resetDrag();
1247
+ this._hideMarker();
1248
+ if (this.options.autofitBounds) {
1249
+ this.fitBounds();
1250
+ }
1251
+ },
1252
+ /**
1253
+ * Hacky way for handling chart resize. Deletes it and redraw chart.
1254
+ */
1255
+ _resizeChart() {
1256
+ if (this._container && style(this._container, "display") != "none") {
1257
+ let opts = this.options;
1258
+ let newWidth = opts.detached ? (this.eleDiv || this._container).offsetWidth : clamp(opts._maxWidth, [0, this._map.getContainer().clientWidth - 30]);
1259
+ if (newWidth) {
1260
+ opts.width = newWidth;
1261
+ if (this._chart && this._chart._chart) {
1262
+ this._chart._chart._resize(opts);
1263
+ this._updateChart();
1264
+ }
1265
+ }
1266
+ this._updateMapSegments();
1267
+ }
1268
+ },
1269
+ /**
1270
+ * Collapse or Expand chart control.
1271
+ */
1272
+ _toggle() {
1273
+ hasClass(this._container, "elevation-expanded") ? this._collapse() : this._expand();
1274
+ },
1275
+ /**
1276
+ * Update map center and zoom (followMarker: true)
1277
+ */
1278
+ _setMapView(item) {
1279
+ if (this._map && this.options.followMarker) {
1280
+ let zoom = this._map.getZoom();
1281
+ let z = this.options.zFollow;
1282
+ if (typeof z === "number") {
1283
+ this._map.setView(item.latlng, zoom < z ? z : zoom, { animate: true, duration: 0.25 });
1284
+ } else if (!this._map.getBounds().contains(item.latlng)) {
1285
+ this._map.setView(item.latlng, zoom, { animate: true, duration: 0.25 });
1286
+ }
1287
+ }
1288
+ },
1289
+ /**
1290
+ * Calculates [x, y] domain and then update chart.
1291
+ */
1292
+ _updateChart() {
1293
+ if (this._chart && this._container) {
1294
+ this.fire("elechart_axis");
1295
+ this._chart.update({ data: this._data, options: this.options });
1296
+ this._x = this._chart._x;
1297
+ this._y = this._chart._y;
1298
+ this.fire("elechart_updated");
1299
+ }
1300
+ },
1301
+ /*
1302
+ * Update the position/height indicator marker drawn onto the map
1303
+ */
1304
+ _updateMarker(item) {
1305
+ if (this._marker) {
1306
+ this._marker.update({
1307
+ map: this._map,
1308
+ item,
1309
+ yCoordMin: this._yCoordMin,
1310
+ yCoordMax: this._yCoordMax || 0,
1311
+ options: this.options
1312
+ });
1313
+ }
1314
+ },
1315
+ /**
1316
+ * Fix marker rotation on rotated maps
1317
+ */
1318
+ _rotateMarker() {
1319
+ if (this._marker) {
1320
+ this._marker.update();
1321
+ }
1322
+ },
1323
+ /**
1324
+ * Highlight track segments on the map.
1325
+ */
1326
+ _updateMapSegments(coords) {
1327
+ this._markedSegments.setLatLngs(coords || []);
1328
+ if (coords && this._map && !this._map.hasLayer(this._markedSegments)) {
1329
+ this._markedSegments.addTo(this._map);
1330
+ }
1331
+ },
1332
+ /**
1333
+ * Update chart summary.
1334
+ */
1335
+ _updateSummary() {
1336
+ if (this._summary) {
1337
+ this._summary.reset();
1338
+ if (this.options.summary) {
1339
+ this.fire("elechart_summary");
1340
+ this._summary.update();
1341
+ }
1342
+ if (this.options.downloadLink && this._downloadURL) {
1343
+ this._summary._container.innerHTML += '<span class="download"><a href="#">' + L._("Download") + "</a></span>";
1344
+ select(".download a", this._summary._container).onclick = (e) => {
1345
+ e.preventDefault();
1346
+ let event = { downloadLink: this.options.downloadLink, confirm: saveFile.bind(this, this._downloadURL) };
1347
+ if (this.options.downloadLink == "modal" && typeof CustomEvent === "function") {
1348
+ document.dispatchEvent(new CustomEvent("eletrack_download", { detail: event }));
1349
+ } else if (this.options.downloadLink == "link" || this.options.downloadLink === true) {
1350
+ event.confirm();
1351
+ }
1352
+ this.fire("eletrack_download", event);
1353
+ };
1354
+ }
1355
+ }
1356
+ },
1357
+ /**
1358
+ * Calculates chart width.
1359
+ */
1360
+ _width() {
1361
+ if (this._chart) return this._chart._width();
1362
+ const { width, margins } = this.options;
1363
+ return width - margins.left - margins.right;
1364
+ },
1365
+ /**
1366
+ * Calculates chart height.
1367
+ */
1368
+ _height() {
1369
+ if (this._chart) return this._chart._height();
1370
+ const { height, margins } = this.options;
1371
+ return height - margins.top - margins.bottom;
1372
+ }
1373
+ });
1374
+
1375
+ // src/index.js
1376
+ Elevation.Utils = utils_exports;
1377
+ L.control.elevation = (options) => new Elevation(options);
1378
+ })();
1709
1379
  //# sourceMappingURL=leaflet-elevation.js.map