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