Repository navigation
Expand file tree
/
Copy pathgpx.js
More file actions
877 lines (777 loc) · 32 KB
/
Copy pathgpx.js
File metadata and controls
877 lines (777 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
/**
* Copyright (C) 2011-2012 Pavel Shramov
* Copyright (C) 2013-2017 Maxime Petazzoni <maxime.petazzoni@bulix.org>
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Thanks to Pavel Shramov who provided the initial implementation and Leaflet
* integration. Original code was at https://github.com/shramov/leaflet-plugins.
*
* It was then cleaned-up and modified to record and make available more
* information about the GPX track while it is being parsed so that the result
* can be used to display additional information about the track that is
* rendered on the Leaflet map.
*/
import { FeatureGroup, Icon, DefaultIcon, Marker, Polyline, LatLng, Util } from 'leaflet';
const _MAX_POINT_INTERVAL_MS = 15000;
const _SECOND_IN_MILLIS = 1000;
const _MINUTE_IN_MILLIS = 60 * _SECOND_IN_MILLIS;
const _HOUR_IN_MILLIS = 60 * _MINUTE_IN_MILLIS;
const _DAY_IN_MILLIS = 24 * _HOUR_IN_MILLIS;
const _GPX_STYLE_NS = 'http://www.topografix.com/GPX/gpx_style/0/2';
const _DEFAULT_ICON = new DefaultIcon();
const _DEFAULT_MARKERS = {
startIcon: _DEFAULT_ICON,
endIcon: _DEFAULT_ICON,
// Based on 'sym' waypoint key
wptIcons: {
'': _DEFAULT_ICON,
},
// Based on 'type' waypoint key
wptTypeIcons: {
'': _DEFAULT_ICON
},
// Based on a regex over the waypoint's name
pointMatchers: [],
};
const _DEFAULT_MARKER_OPTS = {
iconSize: [33, 45],
iconAnchor: [16, 45],
clickable: false
};
const _DEFAULT_POLYLINE_OPTS = {
color: 'blue'
};
const _DEFAULT_GPX_OPTS = {
parseElements: ['track', 'route', 'waypoint'],
joinTrackSegments: true
};
export class GPX extends FeatureGroup {
constructor(gpx, options) {
super();
options = options || {};
options.max_point_interval = options.max_point_interval || _MAX_POINT_INTERVAL_MS;
options.markers = Object.assign({}, _DEFAULT_MARKERS, options.markers || {});
// Optional TypeScript fields may be explicitly undefined. Treat container
// fields that way just like omitted fields, without changing null icons.
for (const key of ['wptIcons', 'wptTypeIcons', 'pointMatchers']) {
if (options.markers[key] === undefined) options.markers[key] = _DEFAULT_MARKERS[key];
}
options.marker_options = Object.assign({}, _DEFAULT_MARKER_OPTS, options.marker_options || {});
options.polyline_options = options.polyline_options || [];
options.gpx_options = Object.assign({}, _DEFAULT_GPX_OPTS, options.gpx_options || {});
if (options.gpx_options.parseElements === undefined) {
options.gpx_options.parseElements = _DEFAULT_GPX_OPTS.parseElements;
}
Util.setOptions(this, options);
this._gpx = gpx;
this._layers = {};
this._prepare_markers(options.markers);
this._init_info();
if (gpx !== undefined) {
this._parse(gpx, options, this.options.async);
}
}
get_duration_string(duration, hidems) {
var s = '';
if (duration >= _DAY_IN_MILLIS) {
s += Math.floor(duration / _DAY_IN_MILLIS) + 'd ';
duration = duration % _DAY_IN_MILLIS;
}
if (duration >= _HOUR_IN_MILLIS) {
s += Math.floor(duration / _HOUR_IN_MILLIS) + ':';
duration = duration % _HOUR_IN_MILLIS;
}
var mins = Math.floor(duration / _MINUTE_IN_MILLIS);
duration = duration % _MINUTE_IN_MILLIS;
if (mins < 10) s += '0';
s += mins + '\'';
var secs = Math.floor(duration / _SECOND_IN_MILLIS);
duration = duration % _SECOND_IN_MILLIS;
if (secs < 10) s += '0';
s += secs;
if (!hidems && duration > 0) s += '.' + Math.round(Math.floor(duration)*1000)/1000;
else s += '"';
return s;
}
get_duration_string_iso(duration, hidems) {
var s = this.get_duration_string(duration, hidems);
return s.replace("'",':').replace('"','');
}
_toFixed_helper(v, unit = 0) {
if (typeof(v) == 'number'){
return v.toFixed(unit);
}
return "?";
}
// Public methods
to_miles(v) { return v / 1.60934; }
to_ft(v) { return v * 3.28084; }
m_to_km(v) { return v / 1000; }
m_to_mi(v) { return v / 1609.34; }
ms_to_kmh(v) { return v * 3.6; }
ms_to_mih(v) { return v / 1609.34 * 3600; }
get_name() { return this._info.name; }
get_desc() { return this._info.desc; }
get_author() { return this._info.author; }
get_copyright() { return this._info.copyright; }
get_distance() { return this._info.length; }
get_distance_imp() { return this.to_miles(this.m_to_km(this.get_distance())); }
get_start_time() { return this._info.duration.start; }
get_end_time() { return this._info.duration.end; }
get_moving_time() { return this._info.duration.moving; }
get_total_time() { return this._info.duration.total; }
get_moving_pace() { return this.get_moving_time() / this.m_to_km(this.get_distance()); }
get_moving_pace_imp() { return this.get_moving_time() / this.get_distance_imp(); }
get_moving_speed() { return this.m_to_km(this.get_distance()) / (this.get_moving_time() / (3600 * 1000)) ; }
get_moving_speed_imp() { return this.to_miles(this.m_to_km(this.get_distance())) / (this.get_moving_time() / (3600 * 1000)) ; }
get_total_speed() { return this.m_to_km(this.get_distance()) / (this.get_total_time() / (3600 * 1000)); }
get_total_speed_imp() { return this.to_miles(this.m_to_km(this.get_distance())) / (this.get_total_time() / (3600 * 1000)); }
get_elevation_gain() { return this._info.elevation.gain; }
get_elevation_loss() { return this._info.elevation.loss; }
get_elevation_gain_imp() { return this.to_ft(this.get_elevation_gain()); }
get_elevation_loss_imp() { return this.to_ft(this.get_elevation_loss()); }
get_elevation_data() {
var _this = this;
return this._info.elevation._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' km, ' + _this._toFixed_helper(b, 0) + ' m'; });
});
}
get_elevation_data_imp() {
var _this = this;
return this._info.elevation._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, _this.to_ft,
function(a, b) { return _this._toFixed_helper(a, 2) + ' mi, ' + _this._toFixed_helper(b, 0) + ' ft'; });
});
}
get_elevation_max() { return this._info.elevation.max; }
get_elevation_min() { return this._info.elevation.min; }
get_elevation_max_imp() { return this.to_ft(this.get_elevation_max()); }
get_elevation_min_imp() { return this.to_ft(this.get_elevation_min()); }
get_speed_data() {
var _this = this;
return this._info.speed._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, _this.ms_to_kmh,
function(a, b) { return _this._toFixed_helper(a, 2) + ' km, ' + _this._toFixed_helper(b, 2) + ' km/h'; });
});
}
get_speed_data_imp() {
var _this = this;
return this._info.speed._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, _this.ms_to_mih,
function(a, b) { return _this._toFixed_helper(a, 2) + ' mi, ' + _this._toFixed_helper(b, 2) + ' mi/h'; });
});
}
get_speed_max() { return this.m_to_km(this._info.speed.max) * 3600; }
get_speed_max_imp() { return this.to_miles(this.get_speed_max()); }
get_average_hr() { return this._info.hr.avg; }
get_average_temp() { return this._info.atemp.avg; }
get_average_cadence() { return this._info.cad.avg; }
get_heartrate_data() {
var _this = this;
return this._info.hr._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' km, ' + _this._toFixed_helper(b, 0) + ' bpm'; });
});
}
get_heartrate_data_imp() {
var _this = this;
return this._info.hr._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' mi, ' + _this._toFixed_helper(b, 0) + ' bpm'; });
});
}
get_cadence_data() {
var _this = this;
return this._info.cad._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' km, ' + _this._toFixed_helper(b, 0) + ' rpm'; });
});
}
get_temp_data() {
var _this = this;
return this._info.atemp._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' km, ' + _this._toFixed_helper(b, 0) + ' degrees'; });
});
}
get_cadence_data_imp() {
var _this = this;
return this._info.cad._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' mi, ' + _this._toFixed_helper(b, 0) + ' rpm'; });
});
}
get_temp_data_imp() {
var _this = this;
return this._info.atemp._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, null,
function(a, b) { return _this._toFixed_helper(a, 2) + ' mi, ' + _this._toFixed_helper(b, 0) + ' degrees'; });
});
}
reload() {
this._init_info();
this.clearLayers();
this._parse(this._gpx, this.options, this.options.async);
}
_prepare_data_point(p, trans1, trans2, trans_tooltip) {
var r = [trans1 && trans1(p[0]) || p[0], trans2 && trans2(p[1]) || p[1]];
r.push(trans_tooltip && trans_tooltip(r[0], r[1]) || (r[0] + ': ' + r[1]));
return r;
}
_prepare_markers(markers) {
const iconize = (url) => {
return new Icon(Object.assign({}, this.options.marker_options, {iconUrl: url}));
}
Object.entries(markers).forEach(([key, value]) => {
if (key === 'wptIcons' || key === 'wptTypeIcons') {
markers[key] = this._prepare_markers(value);
} else if (key === 'pointMatchers') {
markers[key] = value.map(e => {
if (typeof(e.icon) === 'string') {
e.icon = iconize(e.icon);
}
return e;
});
} else if (typeof(value) === 'string') {
markers[key] = iconize(value);
} else if (typeof(value) === 'object' && value !== null) {
markers[key] = value;
}
});
return markers;
}
_init_info() {
this._info = {
name: null,
length: 0.0,
elevation: {gain: 0.0, loss: 0.0, max: 0.0, min: Infinity, _points: []},
speed : {max: 0.0, _points: []},
hr: {avg: 0, _total: 0, _points: []},
duration: {start: null, end: null, moving: 0, total: 0},
atemp: {avg: 0, _total: 0, _points: []},
cad: {avg: 0, _total: 0, _points: []}
};
}
_load_xml(url, cb, options, async, fail, current) {
if (async === undefined) async = this.options.async;
if (options === undefined) options = this.options;
// We ignore 'async' param essentially because fetch is always async.
Promise.resolve().then(() => fetch(url))
.then(response => {
if (!response.ok) {
throw new Error('Error fetching resource: ' + url + ' (' + response.statusText + ')');
}
return response.text();
})
.then(str => {
if (!current()) return;
const parser = new window.DOMParser();
cb(parser.parseFromString(str.trimStart(), "text/xml"), options);
})
.catch(e => {
fail('Error loading GPX: ' + e);
});
}
_xml_parse_error(doc) {
if (!doc) return 'Invalid XML: the response could not be parsed as XML';
if (!doc.documentElement) {
return 'Invalid XML: the document is empty';
}
var el = doc.getElementsByTagNameNS('*', 'parsererror');
if (!el.length) {
if (doc.documentElement.localName !== 'gpx') return 'Invalid GPX: expected a <gpx> root element';
var version = doc.documentElement.getAttribute('version');
if (version && version !== '1.0' && version !== '1.1') return 'Invalid GPX: unsupported version ' + version;
return null;
}
var details = (el[0].textContent || '').trim().replace(/\s+/g, ' ');
if (details.length > 200) details = details.substring(0, 200) + '...';
return 'Invalid XML: ' + details;
}
_parse(input, options, async) {
var _this = this;
var generation = this._parse_generation = (this._parse_generation || 0) + 1;
var current = function() { return generation === _this._parse_generation; };
var completed = false;
var finish = function(event, data) {
if (!current() || completed) return;
completed = true;
// Listener exceptions belong to the caller, not to the transport/parser.
setTimeout(function() { if (current()) _this.fire(event, data); });
};
var fail = function(message) { finish('error', { err: message }); };
var cb = function(gpx, options) {
if (!current() || completed) return;
try {
var parseError = _this._xml_parse_error(gpx);
if (parseError) throw new Error(parseError);
var layers = _this._parse_gpx_data(gpx, options, current);
if (!current()) return;
if (!layers) throw new Error('No parseable layers of type(s) ' + JSON.stringify(options.gpx_options.parseElements));
_this.addLayer(layers);
} catch (e) {
if (!current()) return;
_this._init_info();
// Leaflet removes the layer before firing layerremove. A throwing
// listener must not interrupt cleanup of the remaining layers or hide
// the original error. Stop if a listener has started a newer parse.
var cleanupErrors = [];
for (var layer of _this.getLayers()) {
if (!current()) return;
try { _this.removeLayer(layer); }
catch (cleanupError) { cleanupErrors.push(cleanupError.toString()); }
}
fail('Error parsing GPX: ' + e + (cleanupErrors.length ? '; cleanup: ' + cleanupErrors.join('; ') : ''));
return;
}
finish('loaded', { layers: layers, element: gpx });
};
try {
if (typeof input !== 'string') throw new Error('Invalid GPX input: expected an XML or URL string');
input = input.trim(); // Includes a leading Unicode BOM.
if (!input) throw new Error('Invalid GPX input: the string is empty');
if (input.charAt(0) === '<') {
var parse = function() {
if (!current()) return;
try {
cb(new window.DOMParser().parseFromString(input, 'text/xml'), options);
} catch (e) {
fail('Error parsing XML: ' + e);
}
};
// Keep synchronous getters, but defer terminal events so listeners can
// be attached after construction. Async also defers addpoint/addline.
if (async) setTimeout(parse);
else parse();
} else {
// Single-line paths remain valid (including extensionless endpoints).
// Do not send obvious file contents to the network as relative URLs.
if (/[\u0000-\u001f\u007f<>]/.test(input) || /^-----BEGIN /.test(input)) {
throw new Error('Invalid GPX input: expected XML or a single-line URL');
}
new URL(input, window.document.baseURI); // Respect <base> and inherited frame URLs.
this._load_xml(input, cb, options, async, fail, current);
}
} catch (e) {
fail(e.toString());
}
}
_point_latlng(el) {
var values = ['lat', 'lon'].map(function(attr) {
var value = el.getAttribute(attr);
if (value === null || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value.trim())) {
throw new Error('Invalid GPX coordinate: <' + el.localName + '> requires numeric ' + attr);
}
return Number(value);
});
if (!Number.isFinite(values[0]) || !Number.isFinite(values[1]) || Math.abs(values[0]) > 90 || Math.abs(values[1]) > 180) {
throw new Error('Invalid GPX coordinate: latitude must be -90..90 and longitude -180..180');
}
return new LatLng(values[0], values[1]);
}
_first_child(el, localName) {
if (!el) return null;
for (var i = 0; i < el.children.length; i++) {
if (el.children[i].localName === localName) return el.children[i];
}
return null;
}
/*
* Find the element carrying a given piece of GPX metadata, looking in the
* places the GPX spec allows it, in order of preference: the metadata block
* (GPX 1.1), directly under <gpx> (GPX 1.0), then the first track or route
* (some files only carry their name there).
*
* We deliberately look at direct children only: <name> also appears on every
* waypoint, track point and route point, and searching the whole document
* made get_name() return the name of the last waypoint instead of the file's.
*/
_find_info_element(xml, localName) {
var root = xml.documentElement;
if (!root) return null;
var candidates = [
this._first_child(this._first_child(root, 'metadata'), localName),
this._first_child(root, localName),
this._first_child(xml.getElementsByTagName('trk')[0], localName),
this._first_child(xml.getElementsByTagName('rte')[0], localName),
];
for (var i = 0; i < candidates.length; i++) {
if (candidates[i]) return candidates[i];
}
return null;
}
_parse_gpx_data(xml, options, current) {
current = current || function() { return true; };
if (!current()) return;
var i, t, l, el, layers = [];
var name = this._find_info_element(xml, 'name');
if (name) {
this._info.name = name.textContent.trim();
}
var desc = this._find_info_element(xml, 'desc');
if (desc) {
this._info.desc = desc.textContent.trim();
}
var author = this._find_info_element(xml, 'author');
if (author) {
var authorName = this._first_child(author, 'name');
this._info.author = (authorName || author).textContent.trim();
}
var copyright = this._find_info_element(xml, 'copyright');
if (copyright) {
this._info.copyright = copyright.textContent.trim();
}
var parseElements = options.gpx_options.parseElements;
if (parseElements.indexOf('route') > -1) {
// routes are <rtept> tags inside <rte> sections
var routes = xml.getElementsByTagName('rte');
for (i = 0; i < routes.length; i++) {
if (!current()) return;
var route = routes[i];
var base_style = this._extract_styling(route);
var polyline_options = this._get_polyline_options(options.polyline_options, i);
var parsed = this._parse_segment(routes[i], options, base_style, polyline_options, 'rtept', current);
if (!current()) return;
layers = layers.concat(parsed);
}
}
if (parseElements.indexOf('track') > -1) {
// tracks are <trkpt> tags in one or more <trkseg> sections in each <trk>
var tracks = xml.getElementsByTagName('trk');
for (i = 0; i < tracks.length; i++) {
if (!current()) return;
var track = tracks[i];
var base_style = this._extract_styling(track);
var polyline_options = this._get_polyline_options(options.polyline_options, i);
if (options.gpx_options.joinTrackSegments) {
var parsed = this._parse_segment(track, options, base_style, polyline_options, 'trkpt', current);
if (!current()) return;
layers = layers.concat(parsed);
} else {
var segments = track.getElementsByTagName('trkseg');
for (var j = 0; j < segments.length; j++) {
if (!current()) return;
var parsed = this._parse_segment(segments[j], options, base_style, polyline_options, 'trkpt', current);
if (!current()) return;
layers = layers.concat(parsed);
}
}
}
}
if (!current()) return;
this._info.hr.avg = Math.round(this._info.hr._total / this._info.hr._points.length);
this._info.cad.avg = Math.round(this._info.cad._total / this._info.cad._points.length);
this._info.atemp.avg = Math.round(this._info.atemp._total / this._info.atemp._points.length);
// parse waypoints and add markers for each of them
if (parseElements.indexOf('waypoint') > -1) {
el = xml.getElementsByTagName('wpt');
for (i = 0; i < el.length; i++) {
if (!current()) return;
var ll = this._point_latlng(el[i]);
var nameEl = el[i].getElementsByTagName('name');
var name = nameEl.length > 0 ? nameEl[0].textContent : '';
var descEl = el[i].getElementsByTagName('desc');
var desc = descEl.length > 0 ? descEl[0].textContent : '';
var symEl = el[i].getElementsByTagName('sym');
var symKey = symEl.length > 0 ? symEl[0].textContent : null;
var typeEl = el[i].getElementsByTagName('type');
var typeKey = typeEl.length > 0 ? typeEl[0].textContent : null;
/*
* Add waypoint marker based on the waypoint symbol key.
*
* First look for a configured icon for that symKey. If not found, look
* for a configured icon URL for that symKey and build an icon from it.
* If none of those match, look through the point matchers for a match
* on the waypoint's name.
*
* Otherwise, fall back to the default icon if one was configured, or
* finally to the default icon URL, if one was configured.
*/
var wptIcons = options.markers.wptIcons;
var wptTypeIcons = options.markers.wptTypeIcons;
var ptMatchers = options.markers.pointMatchers || [];
var symIcon;
if (wptIcons && symKey && wptIcons[symKey]) {
symIcon = wptIcons[symKey];
} else if (wptTypeIcons && typeKey && wptTypeIcons[typeKey]) {
symIcon = wptTypeIcons[typeKey];
} else if (ptMatchers.length > 0) {
for (var j = 0; j < ptMatchers.length; j++) {
if (ptMatchers[j].regex.test(name)) {
symIcon = ptMatchers[j].icon;
break;
}
}
} else if (wptIcons && wptIcons['']) {
symIcon = wptIcons[''];
}
if (!symIcon) {
console.log(
'No waypoint icon could be matched for symKey=%s,typeKey=%s,name=%s on waypoint %o',
symKey, typeKey, name, el[i]);
continue;
}
var marker = new Marker(ll, {
clickable: options.marker_options.clickable,
title: name,
icon: symIcon,
type: 'waypoint'
});
var safeName = this._escape_html(name);
var safeDesc = this._escape_html(desc);
marker.bindPopup("<b>" + safeName + "</b>" + (safeDesc.length > 0 ? '<br>' + safeDesc : '')).openPopup();
this.fire('addpoint', { point: marker, point_type: 'waypoint', element: el[i] });
if (!current()) return;
layers.push(marker);
}
}
if (layers.length > 1) {
return new FeatureGroup(layers);
} else if (layers.length == 1) {
return layers[0];
}
}
_escape_html(text) {
return String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
_parse_segment(line, options, base_style, polyline_options, tag, current) {
current = current || function() { return true; };
if (!current()) return [];
var el = line.getElementsByTagName(tag);
if (!el.length) return [];
var coords = [];
var markers = [];
var layers = [];
var last = null;
for (var i = 0; i < el.length; i++) {
if (!current()) return [];
var _, ll = this._point_latlng(el[i]);
ll.meta = { time: null, ele: null, hr: null, cad: null, atemp: null, speed: null };
_ = el[i].getElementsByTagName('time');
if (_.length > 0) {
ll.meta.time = new Date(Date.parse(_[0].textContent));
} else {
ll.meta.time = new Date('1970-01-01T00:00:00');
}
var time_diff = last != null ? Math.abs(ll.meta.time - last.meta.time) : 0;
_ = el[i].getElementsByTagName('ele');
if (_.length > 0) {
ll.meta.ele = parseFloat(_[0].textContent);
} else {
// If the point doesn't have an <ele> tag, assume it has the same
// elevation as the point before it (if it had one).
ll.meta.ele = last != null ? last.meta.ele : null;
}
var ele_diff = last != null ? ll.meta.ele - last.meta.ele : 0;
var dist_3d = last != null ? this._dist3d(last, ll) : 0;
_ = el[i].getElementsByTagName('speed');
if (_.length > 0) {
ll.meta.speed = parseFloat(_[0].textContent);
} else {
// speed in meter per second
ll.meta.speed = time_diff > 0 ? 1000.0 * dist_3d / time_diff : 0;
}
_ = el[i].getElementsByTagName('name');
if (_.length > 0) {
var name = _[0].textContent;
var ptMatchers = options.markers.pointMatchers || [];
for (var j = 0; j < ptMatchers.length; j++) {
if (ptMatchers[j].regex.test(name)) {
markers.push({ label: name, coords: ll, icon: ptMatchers[j].icon, element: el[i] });
break;
}
}
}
this._info.length += dist_3d;
_ = el[i].getElementsByTagNameNS('*', 'hr');
if (_.length > 0) {
ll.meta.hr = parseInt(_[0].textContent);
this._info.hr._points.push([this._info.length, ll.meta.hr]);
this._info.hr._total += ll.meta.hr;
}
_ = el[i].getElementsByTagNameNS('*', 'cad');
if (_.length > 0) {
ll.meta.cad = parseInt(_[0].textContent);
this._info.cad._points.push([this._info.length, ll.meta.cad]);
this._info.cad._total += ll.meta.cad;
}
_ = el[i].getElementsByTagNameNS('*', 'atemp');
if (_.length > 0) {
ll.meta.atemp = parseInt(_[0].textContent);
this._info.atemp._points.push([this._info.length, ll.meta.atemp]);
this._info.atemp._total += ll.meta.atemp;
}
if (ll.meta.ele > this._info.elevation.max) {
this._info.elevation.max = ll.meta.ele;
}
if (ll.meta.ele < this._info.elevation.min) {
this._info.elevation.min = ll.meta.ele;
}
this._info.elevation._points.push([this._info.length, ll.meta.ele]);
if (ll.meta.speed > this._info.speed.max) {
this._info.speed.max = ll.meta.speed;
}
this._info.speed._points.push([this._info.length, ll.meta.speed]);
if ((last == null) && (this._info.duration.start == null)) {
this._info.duration.start = ll.meta.time;
}
this._info.duration.end = ll.meta.time;
this._info.duration.total += time_diff;
if (time_diff < options.max_point_interval) {
this._info.duration.moving += time_diff;
}
if (ele_diff > 0) {
this._info.elevation.gain += ele_diff;
} else {
this._info.elevation.loss += Math.abs(ele_diff);
}
last = ll;
coords.push(ll);
}
// add track
var l = new Polyline(coords, this._extract_styling(line, base_style, polyline_options));
this.fire('addline', { line: l, element: line });
// A listener may synchronously reload this layer. Do not resume the old
// parse: its remaining events and statistics belong to a stale generation.
if (!current()) return [];
layers.push(l);
if (options.markers.startIcon) {
// add start pin
var marker = new Marker(coords[0], {
clickable: options.marker_options.clickable,
icon: options.markers.startIcon,
});
this.fire('addpoint', { point: marker, point_type: 'start', element: el[0], line: line });
if (!current()) return [];
layers.push(marker);
}
if (options.markers.endIcon) {
// add end pin
var marker = new Marker(coords[coords.length-1], {
clickable: options.marker_options.clickable,
icon: options.markers.endIcon,
});
this.fire('addpoint', { point: marker, point_type: 'end', element: el[el.length-1], line: line });
if (!current()) return [];
layers.push(marker);
}
// add named markers
for (var i = 0; i < markers.length; i++) {
if (!current()) return [];
var marker = new Marker(markers[i].coords, {
clickable: options.marker_options.clickable,
title: markers[i].label,
icon: markers[i].icon
});
this.fire('addpoint', { point: marker, point_type: 'label', element: markers[i].element });
if (!current()) return [];
layers.push(marker);
}
return layers;
}
_get_polyline_options(polyline_options, i) {
/*
* Handle backwards compatibility with polyline_options being provided as a single object.
* In this situation, the provided style is expected to apply to all routes and tracks in the file.
*/
if (! Array.isArray(polyline_options)) {
return polyline_options;
}
return polyline_options[i] || {};
}
_extract_styling(el, base, overrides) {
var style = Object.assign({}, _DEFAULT_POLYLINE_OPTS, base);
var e = el.getElementsByTagNameNS(_GPX_STYLE_NS, 'line');
if (e.length > 0) {
var line = e[0];
var _ = line.getElementsByTagName('color');
if (_.length > 0) style.color = '#' + _[0].textContent;
_ = line.getElementsByTagName('opacity');
if (_.length > 0) {
var opacity = parseFloat(_[0].textContent);
if (!isNaN(opacity)) style.opacity = opacity;
}
// GPX Style spec uses <width>; fall back to <weight> for backward compat
_ = line.getElementsByTagName('width');
if (_.length === 0) _ = line.getElementsByTagName('weight');
if (_.length > 0) {
var width = parseFloat(_[0].textContent);
if (!isNaN(width)) style.weight = width;
}
_ = line.getElementsByTagName('linecap');
if (_.length > 0) style.lineCap = _[0].textContent;
_ = line.getElementsByTagName('linejoin');
if (_.length > 0) style.lineJoin = _[0].textContent;
// GPX Style spec uses <dasharray><dash mark="x" space="y"/>...</dasharray>;
// fall back to reading textContent for backward compat
_ = line.getElementsByTagName('dasharray');
if (_.length > 0) {
var dashes = _[0].getElementsByTagName('dash');
if (dashes.length > 0) {
var parts = [];
for (var i = 0; i < dashes.length; i++) {
parts.push(dashes[i].getAttribute('mark') || '0');
parts.push(dashes[i].getAttribute('space') || '0');
}
style.dashArray = parts.join(',');
} else {
style.dashArray = _[0].textContent;
}
}
_ = line.getElementsByTagName('dashoffset');
if (_.length > 0) style.dashOffset = _[0].textContent;
}
return Object.assign(style, overrides);
}
_dist2d(a, b) {
var R = 6371000;
var dLat = this._deg2rad(b.lat - a.lat);
var dLon = this._deg2rad(b.lng - a.lng);
var r = Math.sin(dLat/2) *
Math.sin(dLat/2) +
Math.cos(this._deg2rad(a.lat)) *
Math.cos(this._deg2rad(b.lat)) *
Math.sin(dLon/2) *
Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(r), Math.sqrt(1-r));
var d = R * c;
return d;
}
_dist3d(a, b) {
var planar = this._dist2d(a, b);
var height = Math.abs(b.meta.ele - a.meta.ele);
return Math.sqrt(Math.pow(planar, 2) + Math.pow(height, 2));
}
_deg2rad(deg) {
return deg * Math.PI / 180;
}
}