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