@tmcw/togeojson 4.7.1-0 → 5.0.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,861 +1,2 @@
1
- // cast array x into numbers
2
- // get the content of a text node, if any
3
- function nodeVal(x) {
4
- if (x && x.normalize) {
5
- x.normalize();
6
- }
7
- return (x && x.textContent) || "";
8
- }
9
-
10
- // one Y child of X, if any, otherwise null
11
- function get1(x, y) {
12
- const n = x.getElementsByTagName(y);
13
- return n.length ? n[0] : null;
14
- }
15
-
16
- function getLineStyle(extensions) {
17
- const style = {};
18
- if (extensions) {
19
- const lineStyle = get1(extensions, "line");
20
- if (lineStyle) {
21
- const color = nodeVal(get1(lineStyle, "color")),
22
- opacity = parseFloat(nodeVal(get1(lineStyle, "opacity"))),
23
- width = parseFloat(nodeVal(get1(lineStyle, "width")));
24
- if (color) style.stroke = color;
25
- if (!isNaN(opacity)) style["stroke-opacity"] = opacity;
26
- // GPX width is in mm, convert to px with 96 px per inch
27
- if (!isNaN(width)) style["stroke-width"] = (width * 96) / 25.4;
28
- }
29
- }
30
- return style;
31
- }
32
-
33
- function getExtensions(node) {
34
- let values = [];
35
- if (node !== null) {
36
- for (let i = 0; i < node.childNodes.length; i++) {
37
- const child = node.childNodes[i];
38
- if (child.nodeType !== 1) continue;
39
- const name = ["heart", "gpxtpx:hr", "hr"].includes(child.nodeName)
40
- ? "heart"
41
- : child.nodeName;
42
- if (name === "gpxtpx:TrackPointExtension") {
43
- // loop again for nested garmin extensions (eg. "gpxtpx:hr")
44
- values = values.concat(getExtensions(child));
45
- } else {
46
- // push custom extension (eg. "power")
47
- const val = nodeVal(child);
48
- values.push([name, isNaN(val) ? val : parseFloat(val)]);
49
- }
50
- }
51
- }
52
- return values;
53
- }
54
-
55
- function getMulti(x, ys) {
56
- const o = {};
57
- let n;
58
- let k;
59
- for (k = 0; k < ys.length; k++) {
60
- n = get1(x, ys[k]);
61
- if (n) o[ys[k]] = nodeVal(n);
62
- }
63
- return o;
64
- }
65
- function getProperties$1(node) {
66
- const prop = getMulti(node, [
67
- "name",
68
- "cmt",
69
- "desc",
70
- "type",
71
- "time",
72
- "keywords",
73
- ]);
74
- // Parse additional data from our Garmin extension(s)
75
- const extensions = node.getElementsByTagNameNS(
76
- "http://www.garmin.com/xmlschemas/GpxExtensions/v3",
77
- "*"
78
- );
79
- for (let i = 0; i < extensions.length; i++) {
80
- const extension = extensions[i];
81
- // Ignore nested extensions, like those on routepoints or trackpoints
82
- if (extension.parentNode.parentNode === node) {
83
- prop[extension.tagName.replace(":", "_")] = nodeVal(extension);
84
- }
85
- }
86
- const links = node.getElementsByTagName("link");
87
- if (links.length) prop.links = [];
88
- for (let i = 0; i < links.length; i++) {
89
- prop.links.push(
90
- Object.assign(
91
- { href: links[i].getAttribute("href") },
92
- getMulti(links[i], ["text", "type"])
93
- )
94
- );
95
- }
96
- return prop;
97
- }
98
-
99
- function coordPair$1(x) {
100
- const ll = [
101
- parseFloat(x.getAttribute("lon")),
102
- parseFloat(x.getAttribute("lat")),
103
- ];
104
- const ele = get1(x, "ele");
105
- const time = get1(x, "time");
106
- if (ele) {
107
- const e = parseFloat(nodeVal(ele));
108
- if (!isNaN(e)) {
109
- ll.push(e);
110
- }
111
- }
112
-
113
- return {
114
- coordinates: ll,
115
- time: time ? nodeVal(time) : null,
116
- extendedValues: getExtensions(get1(x, "extensions")),
117
- };
118
- }
119
- function getRoute(node) {
120
- const line = getPoints$1(node, "rtept");
121
- if (!line) return;
122
- return {
123
- type: "Feature",
124
- properties: Object.assign(
125
- getProperties$1(node),
126
- getLineStyle(get1(node, "extensions")),
127
- { _gpxType: "rte" }
128
- ),
129
- geometry: {
130
- type: "LineString",
131
- coordinates: line.line,
132
- },
133
- };
134
- }
135
-
136
- function getPoints$1(node, pointname) {
137
- const pts = node.getElementsByTagName(pointname);
138
- if (pts.length < 2) return; // Invalid line in GeoJSON
139
-
140
- const line = [];
141
- const times = [];
142
- const extendedValues = {};
143
- for (let i = 0; i < pts.length; i++) {
144
- const c = coordPair$1(pts[i]);
145
- line.push(c.coordinates);
146
- if (c.time) times.push(c.time);
147
- for (let j = 0; j < c.extendedValues.length; j++) {
148
- const [name, val] = c.extendedValues[j];
149
- const plural =
150
- name === "heart" ? name : name.replace("gpxtpx:", "") + "s";
151
- if (!extendedValues[plural]) {
152
- extendedValues[plural] = Array(pts.length).fill(null);
153
- }
154
- extendedValues[plural][i] = val;
155
- }
156
- }
157
- return {
158
- line: line,
159
- times: times,
160
- extendedValues: extendedValues,
161
- };
162
- }
163
-
164
- function getTrack(node) {
165
- const segments = node.getElementsByTagName("trkseg");
166
- const track = [];
167
- const times = [];
168
- const extractedLines = [];
169
-
170
- for (let i = 0; i < segments.length; i++) {
171
- const line = getPoints$1(segments[i], "trkpt");
172
- if (line) {
173
- extractedLines.push(line);
174
- if (line.times && line.times.length) times.push(line.times);
175
- }
176
- }
177
-
178
- if (extractedLines.length === 0) return;
179
-
180
- const multi = extractedLines.length > 1;
181
-
182
- const properties = Object.assign(
183
- getProperties$1(node),
184
- getLineStyle(get1(node, "extensions")),
185
- { _gpxType: "trk" },
186
- times.length
187
- ? {
188
- coordinateProperties: {
189
- times: multi ? times : times[0],
190
- },
191
- }
192
- : {}
193
- );
194
-
195
- for (let i = 0; i < extractedLines.length; i++) {
196
- const line = extractedLines[i];
197
- track.push(line.line);
198
- for (const [name, val] of Object.entries(line.extendedValues)) {
199
- if (!properties.coordinateProperties) {
200
- properties.coordinateProperties = {};
201
- }
202
- const props = properties.coordinateProperties;
203
- if (multi) {
204
- if (!props[name])
205
- props[name] = extractedLines.map((line) =>
206
- new Array(line.line.length).fill(null)
207
- );
208
- props[name][i] = val;
209
- } else {
210
- props[name] = val;
211
- }
212
- }
213
- }
214
-
215
- return {
216
- type: "Feature",
217
- properties: properties,
218
- geometry: multi
219
- ? {
220
- type: "MultiLineString",
221
- coordinates: track,
222
- }
223
- : {
224
- type: "LineString",
225
- coordinates: track[0],
226
- },
227
- };
228
- }
229
-
230
- function getPoint(node) {
231
- return {
232
- type: "Feature",
233
- properties: Object.assign(getProperties$1(node), getMulti(node, ["sym"])),
234
- geometry: {
235
- type: "Point",
236
- coordinates: coordPair$1(node).coordinates,
237
- },
238
- };
239
- }
240
-
241
- function* gpxGen(doc) {
242
- const tracks = doc.getElementsByTagName("trk");
243
- const routes = doc.getElementsByTagName("rte");
244
- const waypoints = doc.getElementsByTagName("wpt");
245
-
246
- for (let i = 0; i < tracks.length; i++) {
247
- const feature = getTrack(tracks[i]);
248
- if (feature) yield feature;
249
- }
250
- for (let i = 0; i < routes.length; i++) {
251
- const feature = getRoute(routes[i]);
252
- if (feature) yield feature;
253
- }
254
- for (let i = 0; i < waypoints.length; i++) {
255
- yield getPoint(waypoints[i]);
256
- }
257
- }
258
-
259
- function gpx(doc) {
260
- return {
261
- type: "FeatureCollection",
262
- features: Array.from(gpxGen(doc)),
263
- };
264
- }
265
-
266
- const EXTENSIONS_NS = "http://www.garmin.com/xmlschemas/ActivityExtension/v2";
267
-
268
- const TRACKPOINT_ATTRIBUTES = [
269
- ["heartRate", "heartRates"],
270
- ["Cadence", "cadences"],
271
- // Extended Trackpoint attributes
272
- ["Speed", "speeds"],
273
- ["Watts", "watts"],
274
- ];
275
-
276
- const LAP_ATTRIBUTES = [
277
- ["TotalTimeSeconds", "totalTimeSeconds"],
278
- ["DistanceMeters", "distanceMeters"],
279
- ["MaximumSpeed", "maxSpeed"],
280
- ["AverageHeartRateBpm", "avgHeartRate"],
281
- ["MaximumHeartRateBpm", "maxHeartRate"],
282
-
283
- // Extended Lap attributes
284
- ["AvgSpeed", "avgSpeed"],
285
- ["AvgWatts", "avgWatts"],
286
- ["MaxWatts", "maxWatts"],
287
- ];
288
-
289
- function fromEntries(arr) {
290
- const obj = {};
291
- for (const [key, value] of arr) {
292
- obj[key] = value;
293
- }
294
- return obj;
295
- }
296
-
297
- function getProperties(node, attributeNames) {
298
- const properties = [];
299
-
300
- for (const [tag, alias] of attributeNames) {
301
- let elem = get1(node, tag);
302
- if (!elem) {
303
- const elements = node.getElementsByTagNameNS(EXTENSIONS_NS, tag);
304
- if (elements.length) {
305
- elem = elements[0];
306
- }
307
- }
308
- const val = parseFloat(nodeVal(elem));
309
- if (!isNaN(val)) {
310
- properties.push([alias, val]);
311
- }
312
- }
313
-
314
- return properties;
315
- }
316
-
317
- function coordPair(x) {
318
- const lon = nodeVal(get1(x, "LongitudeDegrees"));
319
- const lat = nodeVal(get1(x, "LatitudeDegrees"));
320
- if (!lon.length || !lat.length) {
321
- return null;
322
- }
323
- const ll = [parseFloat(lon), parseFloat(lat)];
324
- const alt = get1(x, "AltitudeMeters");
325
- const heartRate = get1(x, "HeartRateBpm");
326
- const time = get1(x, "Time");
327
- let a;
328
- if (alt) {
329
- a = parseFloat(nodeVal(alt));
330
- if (!isNaN(a)) {
331
- ll.push(a);
332
- }
333
- }
334
- return {
335
- coordinates: ll,
336
- time: time ? nodeVal(time) : null,
337
- heartRate: heartRate ? parseFloat(nodeVal(heartRate)) : null,
338
- extensions: getProperties(x, TRACKPOINT_ATTRIBUTES),
339
- };
340
- }
341
-
342
- function getPoints(node, pointname) {
343
- const pts = node.getElementsByTagName(pointname);
344
- const line = [];
345
- const times = [];
346
- const heartRates = [];
347
- if (pts.length < 2) return null; // Invalid line in GeoJSON
348
- const result = { extendedProperties: {} };
349
- for (let i = 0; i < pts.length; i++) {
350
- const c = coordPair(pts[i]);
351
- if (c === null) continue;
352
- line.push(c.coordinates);
353
- if (c.time) times.push(c.time);
354
- if (c.heartRate) heartRates.push(c.heartRate);
355
- for (const [alias, value] of c.extensions) {
356
- if (!result.extendedProperties[alias]) {
357
- result.extendedProperties[alias] = Array(pts.length).fill(null);
358
- }
359
- result.extendedProperties[alias][i] = value;
360
- }
361
- }
362
- return Object.assign(result, {
363
- line: line,
364
- times: times,
365
- heartRates: heartRates,
366
- });
367
- }
368
-
369
- function getLap(node) {
370
- const segments = node.getElementsByTagName("Track");
371
- const track = [];
372
- const times = [];
373
- const heartRates = [];
374
- const allExtendedProperties = [];
375
- let line;
376
- const properties = fromEntries(getProperties(node, LAP_ATTRIBUTES));
377
-
378
- const nameElement = get1(node, "Name");
379
- if (nameElement) {
380
- properties.name = nodeVal(nameElement);
381
- }
382
-
383
- for (let i = 0; i < segments.length; i++) {
384
- line = getPoints(segments[i], "Trackpoint");
385
- if (line) {
386
- track.push(line.line);
387
- if (line.times.length) times.push(line.times);
388
- if (line.heartRates.length) heartRates.push(line.heartRates);
389
- allExtendedProperties.push(line.extendedProperties);
390
- }
391
- }
392
- for (let i = 0; i < allExtendedProperties.length; i++) {
393
- const extendedProperties = allExtendedProperties[i];
394
- for (const property in extendedProperties) {
395
- if (segments.length === 1) {
396
- properties[property] = line.extendedProperties[property];
397
- } else {
398
- if (!properties[property]) {
399
- properties[property] = track.map((track) =>
400
- Array(track.length).fill(null)
401
- );
402
- }
403
- properties[property][i] = extendedProperties[property];
404
- }
405
- }
406
- }
407
- if (track.length === 0) return;
408
-
409
- if (times.length || heartRates.length) {
410
- properties.coordinateProperties = Object.assign(
411
- times.length
412
- ? {
413
- times: track.length === 1 ? times[0] : times,
414
- }
415
- : {},
416
- heartRates.length
417
- ? {
418
- heart: track.length === 1 ? heartRates[0] : heartRates,
419
- }
420
- : {}
421
- );
422
- }
423
-
424
- return {
425
- type: "Feature",
426
- properties: properties,
427
- geometry: {
428
- type: track.length === 1 ? "LineString" : "MultiLineString",
429
- coordinates: track.length === 1 ? track[0] : track,
430
- },
431
- };
432
- }
433
-
434
- function* tcxGen(doc) {
435
- const laps = doc.getElementsByTagName("Lap");
436
-
437
- for (let i = 0; i < laps.length; i++) {
438
- const feature = getLap(laps[i]);
439
- if (feature) yield feature;
440
- }
441
-
442
- const courses = doc.getElementsByTagName("Courses");
443
-
444
- for (let i = 0; i < courses.length; i++) {
445
- const feature = getLap(courses[i]);
446
- if (feature) yield feature;
447
- }
448
- }
449
-
450
- function tcx(doc) {
451
- return {
452
- type: "FeatureCollection",
453
- features: Array.from(tcxGen(doc)),
454
- };
455
- }
456
-
457
- const removeSpace = /\s*/g;
458
- const trimSpace = /^\s*|\s*$/g;
459
- const splitSpace = /\s+/;
460
-
461
- // generate a short, numeric hash of a string
462
- function okhash(x) {
463
- if (!x || !x.length) return 0;
464
- let h = 0;
465
- for (let i = 0; i < x.length; i++) {
466
- h = ((h << 5) - h + x.charCodeAt(i)) | 0;
467
- }
468
- return h;
469
- }
470
-
471
- // get one coordinate from a coordinate array, if any
472
- function coord1(v) {
473
- return v.replace(removeSpace, "").split(",").map(parseFloat);
474
- }
475
-
476
- // get all coordinates from a coordinate array as [[],[]]
477
- function coord(v) {
478
- return v.replace(trimSpace, "").split(splitSpace).map(coord1);
479
- }
480
-
481
- function xml2str(node) {
482
- if (node.xml !== undefined) return node.xml;
483
- if (node.tagName) {
484
- let output = node.tagName;
485
- for (let i = 0; i < node.attributes.length; i++) {
486
- output += node.attributes[i].name + node.attributes[i].value;
487
- }
488
- for (let i = 0; i < node.childNodes.length; i++) {
489
- output += xml2str(node.childNodes[i]);
490
- }
491
- return output;
492
- }
493
- if (node.nodeName === "#text") {
494
- return (node.nodeValue || node.value || "").trim();
495
- }
496
- if (node.nodeName === "#cdata-section") {
497
- return node.nodeValue;
498
- }
499
- return "";
500
- }
501
-
502
- const geotypes = ["Polygon", "LineString", "Point", "Track", "gx:Track"];
503
-
504
- function kmlColor(properties, elem, prefix) {
505
- let v = nodeVal(get1(elem, "color")) || "";
506
- const colorProp =
507
- prefix == "stroke" || prefix === "fill" ? prefix : prefix + "-color";
508
- if (v.substr(0, 1) === "#") {
509
- v = v.substr(1);
510
- }
511
- if (v.length === 6 || v.length === 3) {
512
- properties[colorProp] = v;
513
- } else if (v.length === 8) {
514
- properties[prefix + "-opacity"] = parseInt(v.substr(0, 2), 16) / 255;
515
- properties[colorProp] =
516
- "#" + v.substr(6, 2) + v.substr(4, 2) + v.substr(2, 2);
517
- }
518
- }
519
-
520
- function numericProperty(properties, elem, source, target) {
521
- const val = parseFloat(nodeVal(get1(elem, source)));
522
- if (!isNaN(val)) properties[target] = val;
523
- }
524
-
525
- function gxCoords(root) {
526
- let elems = root.getElementsByTagName("coord");
527
- const coords = [];
528
- const times = [];
529
- if (elems.length === 0) elems = root.getElementsByTagName("gx:coord");
530
- for (let i = 0; i < elems.length; i++) {
531
- coords.push(nodeVal(elems[i]).split(" ").map(parseFloat));
532
- }
533
- const timeElems = root.getElementsByTagName("when");
534
- for (let j = 0; j < timeElems.length; j++) times.push(nodeVal(timeElems[j]));
535
- return {
536
- coords: coords,
537
- times: times,
538
- };
539
- }
540
-
541
- function getGeometry(root) {
542
- let geomNode;
543
- let geomNodes;
544
- let i;
545
- let j;
546
- let k;
547
- const geoms = [];
548
- const coordTimes = [];
549
- if (get1(root, "MultiGeometry")) {
550
- return getGeometry(get1(root, "MultiGeometry"));
551
- }
552
- if (get1(root, "MultiTrack")) {
553
- return getGeometry(get1(root, "MultiTrack"));
554
- }
555
- if (get1(root, "gx:MultiTrack")) {
556
- return getGeometry(get1(root, "gx:MultiTrack"));
557
- }
558
- for (i = 0; i < geotypes.length; i++) {
559
- geomNodes = root.getElementsByTagName(geotypes[i]);
560
- if (geomNodes) {
561
- for (j = 0; j < geomNodes.length; j++) {
562
- geomNode = geomNodes[j];
563
- if (geotypes[i] === "Point") {
564
- geoms.push({
565
- type: "Point",
566
- coordinates: coord1(nodeVal(get1(geomNode, "coordinates"))),
567
- });
568
- } else if (geotypes[i] === "LineString") {
569
- geoms.push({
570
- type: "LineString",
571
- coordinates: coord(nodeVal(get1(geomNode, "coordinates"))),
572
- });
573
- } else if (geotypes[i] === "Polygon") {
574
- const rings = geomNode.getElementsByTagName("LinearRing"),
575
- coords = [];
576
- for (k = 0; k < rings.length; k++) {
577
- coords.push(coord(nodeVal(get1(rings[k], "coordinates"))));
578
- }
579
- geoms.push({
580
- type: "Polygon",
581
- coordinates: coords,
582
- });
583
- } else if (geotypes[i] === "Track" || geotypes[i] === "gx:Track") {
584
- const track = gxCoords(geomNode);
585
- geoms.push({
586
- type: "LineString",
587
- coordinates: track.coords,
588
- });
589
- if (track.times.length) coordTimes.push(track.times);
590
- }
591
- }
592
- }
593
- }
594
- return {
595
- geoms: geoms,
596
- coordTimes: coordTimes,
597
- };
598
- }
599
-
600
- function getPlacemark(root, styleIndex, styleMapIndex, styleByHash) {
601
- const geomsAndTimes = getGeometry(root);
602
- let i;
603
- const properties = {};
604
- const name = nodeVal(get1(root, "name"));
605
- const address = nodeVal(get1(root, "address"));
606
- let styleUrl = nodeVal(get1(root, "styleUrl"));
607
- const description = nodeVal(get1(root, "description"));
608
- const timeSpan = get1(root, "TimeSpan");
609
- const timeStamp = get1(root, "TimeStamp");
610
- const extendedData = get1(root, "ExtendedData");
611
- let iconStyle = get1(root, "IconStyle");
612
- let labelStyle = get1(root, "LabelStyle");
613
- let lineStyle = get1(root, "LineStyle");
614
- let polyStyle = get1(root, "PolyStyle");
615
- const visibility = get1(root, "visibility");
616
-
617
- if (name) properties.name = name;
618
- if (address) properties.address = address;
619
- if (styleUrl) {
620
- if (styleUrl[0] !== "#") {
621
- styleUrl = "#" + styleUrl;
622
- }
623
-
624
- properties.styleUrl = styleUrl;
625
- if (styleIndex[styleUrl]) {
626
- properties.styleHash = styleIndex[styleUrl];
627
- }
628
- if (styleMapIndex[styleUrl]) {
629
- properties.styleMapHash = styleMapIndex[styleUrl];
630
- properties.styleHash = styleIndex[styleMapIndex[styleUrl].normal];
631
- }
632
- // Try to populate the lineStyle or polyStyle since we got the style hash
633
- const style = styleByHash[properties.styleHash];
634
- if (style) {
635
- if (!iconStyle) iconStyle = get1(style, "IconStyle");
636
- if (!labelStyle) labelStyle = get1(style, "LabelStyle");
637
- if (!lineStyle) lineStyle = get1(style, "LineStyle");
638
- if (!polyStyle) polyStyle = get1(style, "PolyStyle");
639
- }
640
- }
641
- if (description) properties.description = description;
642
- if (timeSpan) {
643
- const begin = nodeVal(get1(timeSpan, "begin"));
644
- const end = nodeVal(get1(timeSpan, "end"));
645
- properties.timespan = { begin: begin, end: end };
646
- }
647
- if (timeStamp) {
648
- properties.timestamp = nodeVal(get1(timeStamp, "when"));
649
- }
650
- if (iconStyle) {
651
- kmlColor(properties, iconStyle, "icon");
652
- numericProperty(properties, iconStyle, "scale", "icon-scale");
653
- numericProperty(properties, iconStyle, "heading", "icon-heading");
654
-
655
- const hotspot = get1(iconStyle, "hotSpot");
656
- if (hotspot) {
657
- const left = parseFloat(hotspot.getAttribute("x"));
658
- const top = parseFloat(hotspot.getAttribute("y"));
659
- if (!isNaN(left) && !isNaN(top)) properties["icon-offset"] = [left, top];
660
- }
661
- const icon = get1(iconStyle, "Icon");
662
- if (icon) {
663
- const href = nodeVal(get1(icon, "href"));
664
- if (href) properties.icon = href;
665
- }
666
- }
667
- if (labelStyle) {
668
- kmlColor(properties, labelStyle, "label");
669
- numericProperty(properties, labelStyle, "scale", "label-scale");
670
- }
671
- if (lineStyle) {
672
- kmlColor(properties, lineStyle, "stroke");
673
- numericProperty(properties, lineStyle, "width", "stroke-width");
674
- }
675
- if (polyStyle) {
676
- kmlColor(properties, polyStyle, "fill");
677
- const fill = nodeVal(get1(polyStyle, "fill"));
678
- const outline = nodeVal(get1(polyStyle, "outline"));
679
- if (fill)
680
- properties["fill-opacity"] =
681
- fill === "1" ? properties["fill-opacity"] || 1 : 0;
682
- if (outline)
683
- properties["stroke-opacity"] =
684
- outline === "1" ? properties["stroke-opacity"] || 1 : 0;
685
- }
686
- if (extendedData) {
687
- const datas = extendedData.getElementsByTagName("Data"),
688
- simpleDatas = extendedData.getElementsByTagName("SimpleData");
689
-
690
- for (i = 0; i < datas.length; i++) {
691
- properties[datas[i].getAttribute("name")] = nodeVal(
692
- get1(datas[i], "value")
693
- );
694
- }
695
- for (i = 0; i < simpleDatas.length; i++) {
696
- properties[simpleDatas[i].getAttribute("name")] = nodeVal(simpleDatas[i]);
697
- }
698
- }
699
- if (visibility) {
700
- properties.visibility = nodeVal(visibility);
701
- }
702
- if (geomsAndTimes.coordTimes.length) {
703
- properties.coordinateProperties = {
704
- times:
705
- geomsAndTimes.coordTimes.length === 1
706
- ? geomsAndTimes.coordTimes[0]
707
- : geomsAndTimes.coordTimes,
708
- };
709
- }
710
- const feature = {
711
- type: "Feature",
712
- geometry:
713
- geomsAndTimes.geoms.length === 0
714
- ? null
715
- : geomsAndTimes.geoms.length === 1
716
- ? geomsAndTimes.geoms[0]
717
- : {
718
- type: "GeometryCollection",
719
- geometries: geomsAndTimes.geoms,
720
- },
721
- properties: properties,
722
- };
723
- if (root.getAttribute("id")) feature.id = root.getAttribute("id");
724
- return feature;
725
- }
726
-
727
- function getFolder(node) {
728
- const props = ["name", "visibility", "description"];
729
- const meta = {};
730
-
731
- for (let i = 0; i < node.childNodes.length; i++) {
732
- const child = node.childNodes[i];
733
- if (props.includes(child.tagName)) {
734
- meta[child.tagName] = nodeVal(child);
735
- }
736
- }
737
-
738
- return {
739
- type: "folder",
740
- meta,
741
- children: [],
742
- };
743
- }
744
-
745
- function buildStyleMap(doc) {
746
- // styleindex keeps track of hashed styles in order to match feature
747
- const styleIndex = {};
748
- const styleByHash = {};
749
-
750
- // stylemapindex keeps track of style maps to expose in properties
751
- const styleMapIndex = {};
752
-
753
- const styles = doc.getElementsByTagName("Style");
754
- const styleMaps = doc.getElementsByTagName("StyleMap");
755
-
756
- for (let k = 0; k < styles.length; k++) {
757
- const style = styles[k];
758
- const hash = okhash(xml2str(style)).toString(16);
759
- let id = style.getAttribute("id");
760
- if (
761
- !id &&
762
- style.parentNode.tagName.replace("gx:", "") === "CascadingStyle"
763
- ) {
764
- id =
765
- style.parentNode.getAttribute("kml:id") ||
766
- style.parentNode.getAttribute("id");
767
- }
768
- styleIndex["#" + id] = hash;
769
- styleByHash[hash] = style;
770
- }
771
- for (let l = 0; l < styleMaps.length; l++) {
772
- styleIndex["#" + styleMaps[l].getAttribute("id")] = okhash(
773
- xml2str(styleMaps[l])
774
- ).toString(16);
775
- const pairs = styleMaps[l].getElementsByTagName("Pair");
776
- const pairsMap = {};
777
- for (let m = 0; m < pairs.length; m++) {
778
- pairsMap[nodeVal(get1(pairs[m], "key"))] = nodeVal(
779
- get1(pairs[m], "styleUrl")
780
- );
781
- }
782
- styleMapIndex["#" + styleMaps[l].getAttribute("id")] = pairsMap;
783
- }
784
- return { styleMapIndex, styleIndex, styleByHash };
785
- }
786
-
787
- /**
788
- * Yield a nested tree with KML folder structure
789
- */
790
- function kmlWithFolders(doc) {
791
- const {
792
- // styleindex keeps track of hashed styles in order to match feature
793
- styleIndex,
794
- styleByHash,
795
- // stylemapindex keeps track of style maps to expose in properties
796
- styleMapIndex,
797
- } = buildStyleMap(doc);
798
- const tree = { type: "root", children: [] };
799
-
800
- function traverse(node, pointer) {
801
- if (node.tagName === "Placemark") {
802
- pointer.children.push(
803
- getPlacemark(node, styleIndex, styleMapIndex, styleByHash)
804
- );
805
- }
806
- if (node.tagName === "Folder") {
807
- const folder = getFolder(node);
808
- pointer.children.push(folder);
809
- pointer = folder;
810
- }
811
-
812
- if (node.childNodes) {
813
- for (let i = 0; i < node.childNodes.length; i++) {
814
- traverse(node.childNodes[i], pointer);
815
- }
816
- }
817
- }
818
-
819
- traverse(doc, tree);
820
-
821
- return tree;
822
- }
823
-
824
- /**
825
- * Yield features, one by one. Does not include
826
- * or care for folders.
827
- */
828
- function* kmlGen(doc) {
829
- const {
830
- // styleindex keeps track of hashed styles in order to match feature
831
- styleIndex,
832
- styleByHash,
833
- // stylemapindex keeps track of style maps to expose in properties
834
- styleMapIndex,
835
- } = buildStyleMap(doc);
836
-
837
- // atomic geospatial types supported by KML - MultiGeometry is
838
- // handled separately
839
- // all root placemarks in the file
840
- const placemarks = doc.getElementsByTagName("Placemark");
841
-
842
- for (let j = 0; j < placemarks.length; j++) {
843
- const feature = getPlacemark(
844
- placemarks[j],
845
- styleIndex,
846
- styleMapIndex,
847
- styleByHash
848
- );
849
- if (feature) yield feature;
850
- }
851
- }
852
-
853
- function kml(doc) {
854
- return {
855
- type: "FeatureCollection",
856
- features: Array.from(kmlGen(doc)),
857
- };
858
- }
859
-
860
- export { gpx, gpxGen, kml, kmlGen, kmlWithFolders, tcx, tcxGen };
1
+ function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function t(t,r){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,r){if(t){if("string"==typeof t)return e(t,r);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e(t,r):void 0}}(t))||r&&t&&"number"==typeof t.length){n&&(t=n);var a=0;return function(){return a>=t.length?{done:!0}:{done:!1,value:t[a++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function r(e,t){return Array.from(e.getElementsByTagName(t))}function n(e){return"#"===e[0]?e:"#"+e}function a(e){return null==e||e.normalize(),e&&e.textContent||""}function i(e,t,r){var n=e.getElementsByTagName(t),a=n.length?n[0]:null;return a&&r&&r(a),a}function o(e,t,r){var n={};if(!e)return n;var a=e.getElementsByTagName(t),i=a.length?a[0]:null;return i&&r?r(i,n):n}function u(e,t,r){var n=a(i(e,t));return n&&r&&r(n)||{}}function s(e,t,r){var n=parseFloat(a(i(e,t)));if(!isNaN(n))return n&&r&&r(n)||{}}function l(e,t,r){var n=parseFloat(a(i(e,t)));if(!isNaN(n))return n&&r&&r(n),n}function c(e,r){for(var n,a={},i=function(){var t=n.value;u(e,t,function(e){a[t]=e})},o=t(r);!(n=o()).done;)i();return a}function f(e){return 1===(null==e?void 0:e.nodeType)}function g(e){return o(e,"line",function(e){return Object.assign({},u(e,"color",function(e){return{stroke:"#"+e}}),s(e,"opacity",function(e){return{"stroke-opacity":e}}),s(e,"width",function(e){return{"stroke-width":96*e/25.4}}))})}function p(e){var t=[];if(null===e)return t;for(var r=0,n=Array.from(e.childNodes);r<n.length;r++){var i=n[r];if(f(i)){var o=d(i.nodeName);if("gpxtpx:TrackPointExtension"===o)t=t.concat(p(i));else{var u=a(i);t.push([o,v(u)])}}}return t}function d(e){return["heart","gpxtpx:hr","hr"].includes(e)?"heart":e}function v(e){var t=parseFloat(e);return isNaN(t)?e:t}function m(e){var t=[parseFloat(e.getAttribute("lon")||""),parseFloat(e.getAttribute("lat")||"")];l(e,"ele",function(e){t.push(e)});var r=i(e,"time");return{coordinates:t,time:r?a(r):null,extendedValues:p(i(e,"extensions"))}}function h(e){for(var t=c(e,["name","cmt","desc","type","time","keywords"]),n=0,i=Array.from(e.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3","*"));n<i.length;n++){var o,u=i[n];(null==(o=u.parentNode)?void 0:o.parentNode)===e&&(t[u.tagName.replace(":","_")]=a(u))}var s=r(e,"link");return s.length&&(t.links=s.map(function(e){return Object.assign({href:e.getAttribute("href")},c(e,["text","type"]))})),t}var y=/*#__PURE__*/regeneratorRuntime.mark(A);function b(e,n){var a=r(e,n);if(!(a.length<2)){for(var i=[],o=[],u={},s=0;s<a.length;s++){var l=m(a[s]);i.push(l.coordinates),l.time&&o.push(l.time);for(var c,f=t(l.extendedValues);!(c=f()).done;){var g=c.value,p=g[0],d=g[1],v="heart"===p?p:p.replace("gpxtpx:","")+"s";u[v]||(u[v]=Array(a.length).fill(null)),u[v][s]=d}}return{line:i,times:o,extendedValues:u}}}function x(e){var t=b(e,"rtept");if(t)return{type:"Feature",properties:Object.assign({_gpxType:"rte"},h(e),g(i(e,"extensions"))),geometry:{type:"LineString",coordinates:t.line}}}function k(e){for(var n,a=[],o=[],u=[],s=t(r(e,"trkseg"));!(n=s()).done;){var l=b(n.value,"trkpt");l&&(u.push(l),l.times&&l.times.length&&o.push(l.times))}if(0===u.length)return null;for(var c=u.length>1,f=Object.assign({_gpxType:"trk"},h(e),g(i(e,"extensions")),o.length?{coordinateProperties:{times:c?o:o[0]}}:{}),p=0,d=u;p<d.length;p++){var v=d[p];a.push(v.line),f.coordinateProperties||(f.coordinateProperties={});for(var m=f.coordinateProperties,y=Object.entries(v.extendedValues),x=0;x<y.length;x++){var k=y[x],N=k[0],A=k[1];c?(m[N]||(m[N]=u.map(function(e){return new Array(e.line.length).fill(null)})),m[N][x]=A):m[N]=A}}return{type:"Feature",properties:f,geometry:c?{type:"MultiLineString",coordinates:a}:{type:"LineString",coordinates:a[0]}}}function N(e){return{type:"Feature",properties:Object.assign(h(e),c(e,["sym"])),geometry:{type:"Point",coordinates:m(e).coordinates}}}function A(e){var n,a,i,o,u,s,l,c,f;return regeneratorRuntime.wrap(function(g){for(;;)switch(g.prev=g.next){case 0:n=t(r(e,"trk"));case 1:if((a=n()).done){g.next=9;break}if(!(i=k(a.value))){g.next=7;break}return g.next=7,i;case 7:g.next=1;break;case 9:o=t(r(e,"rte"));case 10:if((u=o()).done){g.next=18;break}if(!(s=x(u.value))){g.next=16;break}return g.next=16,s;case 16:g.next=10;break;case 18:l=t(r(e,"wpt"));case 19:if((c=l()).done){g.next=25;break}return f=c.value,g.next=23,N(f);case 23:g.next=19;break;case 25:case"end":return g.stop()}},y)}function S(e){return{type:"FeatureCollection",features:Array.from(A(e))}}var w=/*#__PURE__*/regeneratorRuntime.mark(L),T=[["heartRate","heartRates"],["Cadence","cadences"],["Speed","speeds"],["Watts","watts"]],F=[["TotalTimeSeconds","totalTimeSeconds"],["DistanceMeters","distanceMeters"],["MaximumSpeed","maxSpeed"],["AverageHeartRateBpm","avgHeartRate"],["MaximumHeartRateBpm","maxHeartRate"],["AvgSpeed","avgSpeed"],["AvgWatts","avgWatts"],["MaxWatts","maxWatts"]];function P(e,r){for(var n,o=[],u=t(r);!(n=u()).done;){var s=n.value,l=s[0],c=s[1],f=i(e,l);if(!f){var g=e.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/ActivityExtension/v2",l);g.length&&(f=g[0])}var p=parseFloat(a(f));isNaN(p)||o.push([c,p])}return o}function j(e){var t=[l(e,"LongitudeDegrees"),l(e,"LatitudeDegrees")];if(void 0===t[0]||isNaN(t[0])||void 0===t[1]||isNaN(t[1]))return null;var r=i(e,"HeartRateBpm"),n=a(i(e,"Time"));return i(e,"AltitudeMeters",function(e){var r=parseFloat(a(e));isNaN(r)||t.push(r)}),{coordinates:t,time:n||null,heartRate:r?parseFloat(a(r)):null,extensions:P(e,T)}}function O(e){var n=r(e,"Trackpoint"),a=[],i=[],o=[];if(n.length<2)return null;for(var u={},s={extendedProperties:u},l=0;l<n.length;l++){var c=j(n[l]);if(null!==c){a.push(c.coordinates);var f=c.time,g=c.heartRate,p=c.extensions;f&&i.push(f),g&&o.push(g);for(var d,v=t(p);!(d=v()).done;){var m=d.value,h=m[0],y=m[1];u[h]||(u[h]=Array(n.length).fill(null)),u[h][l]=y}}}return Object.assign(s,{line:a,times:i,heartRates:o})}function R(e){for(var n,i,u=r(e,"Track"),s=[],l=[],c=[],f=[],g=Object.assign(Object.fromEntries(P(e,F)),o(e,"Name",function(e){return{name:a(e)}})),p=t(u);!(i=p()).done;)(n=O(i.value))&&(s.push(n.line),n.times.length&&l.push(n.times),n.heartRates.length&&c.push(n.heartRates),f.push(n.extendedProperties));for(var d=0;d<f.length;d++){var v=f[d];for(var m in v)1===u.length?n&&(g[m]=n.extendedProperties[m]):(g[m]||(g[m]=s.map(function(e){return Array(e.length).fill(null)})),g[m][d]=v[m])}return 0===s.length?null:((l.length||c.length)&&(g.coordinateProperties=Object.assign(l.length?{times:1===s.length?l[0]:l}:{},c.length?{heart:1===s.length?c[0]:c}:{})),{type:"Feature",properties:g,geometry:1===s.length?{type:"LineString",coordinates:s[0]}:{type:"MultiLineString",coordinates:s}})}function L(e){var n,a,i,o,u,s;return regeneratorRuntime.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:n=t(r(e,"Lap"));case 1:if((a=n()).done){l.next=9;break}if(!(i=R(a.value))){l.next=7;break}return l.next=7,i;case 7:l.next=1;break;case 9:o=t(r(e,"Courses"));case 10:if((u=o()).done){l.next=18;break}if(!(s=R(u.value))){l.next=16;break}return l.next=16,s;case 16:l.next=10;break;case 18:case"end":return l.stop()}},w)}function M(e){return{type:"FeatureCollection",features:Array.from(L(e))}}function E(e,t){var r={},n="stroke"==t||"fill"===t?t:t+"-color";return"#"===e[0]&&(e=e.substring(1)),6===e.length||3===e.length?r[n]="#"+e:8===e.length&&(r[t+"-opacity"]=parseInt(e.substring(0,2),16)/255,r[n]="#"+e.substring(6,8)+e.substring(4,6)+e.substring(2,4)),r}function B(e,t,r){var n={};return l(e,t,function(e){n[r]=e}),n}function C(e,t){return o(e,"color",function(e){return E(a(e),t)})}function D(e){return Object.assign({},function(e){return o(e,"PolyStyle",function(e,t){return Object.assign(t,o(e,"color",function(e){return E(a(e),"fill")}),u(e,"fill",function(e){if("0"===e)return{"fill-opacity":0}}),u(e,"outline",function(e){if("0"===e)return{"stroke-opacity":0}}))})}(e),function(e){return o(e,"LineStyle",function(t){return Object.assign(C(e,"stroke"),B(t,"width","stroke-width"))})}(e),function(e){return o(e,"LabelStyle",function(t){return Object.assign(C(e,"label"),B(t,"scale","label-scale"))})}(e),function(e){return o(e,"IconStyle",function(t){return Object.assign(C(e,"icon"),B(t,"scale","icon-scale"),B(t,"heading","icon-heading"),o(t,"hotSpot",function(e){var t=parseFloat(e.getAttribute("x")||""),r=parseFloat(e.getAttribute("y")||"");return isNaN(t)||isNaN(r)?{}:{"icon-offset":[t,r]}}),o(t,"Icon",function(e,t){return u(e,"href",function(e){t.icon=e}),t}))})}(e))}var I=/\s*/g,H=/^\s*|\s*$/g,U=/\s+/;function W(e){return e.replace(I,"").split(",").map(parseFloat).filter(function(e){return!isNaN(e)})}function V(e){return e.replace(H,"").split(U).map(W).filter(function(e){return e.length>=2})}function G(e){var t=r(e,"coord");0===t.length&&(t=Array.from(e.getElementsByTagNameNS("*","coord")));var n=t.map(function(e){return a(e).split(" ").map(parseFloat)});return 0===n.length?null:{geometry:n.length>2?{type:"LineString",coordinates:n}:{type:"Point",coordinates:n[0]},times:r(e,"when").map(function(e){return a(e)})}}function _(e){if(0===e.length)return e;for(var t=e[0],r=e[e.length-1],n=!0,a=0;a<Math.max(t.length,r.length);a++)if(t[a]!==r[a]){n=!1;break}return n?e:e.concat([e[0]])}var $=["Polygon","LineString","Point","Track","gx:Track"];function z(e){return a(i(e,"coordinates"))}function q(e){for(var n=[],a=[],o=0,u=["MultiGeometry","MultiTrack","gx:MultiTrack"];o<u.length;o++){var s=i(e,u[o]);if(s)return q(s)}for(var l,c=t($);!(l=c()).done;)for(var f,g=l.value,p=t(r(e,g));!(f=p()).done;){var d=f.value;switch(g){case"Point":var v=W(z(d));v.length>=2&&n.push({type:"Point",coordinates:v});break;case"LineString":var m=V(z(d));m.length>=2&&n.push({type:"LineString",coordinates:m});break;case"Polygon":for(var h,y=[],b=t(r(d,"LinearRing"));!(h=b()).done;){var x=_(V(z(h.value)));x.length>=4&&y.push(x)}y.length&&n.push({type:"Polygon",coordinates:y});break;case"Track":case"gx:Track":var k=G(d);if(!k)break;var N=k.times;n.push(k.geometry),N.length&&a.push(N)}}return{geometries:n,coordTimes:a}}function J(e){return o(e,"ExtendedData",function(e,n){for(var o,u=t(r(e,"Data"));!(o=u()).done;){var s=o.value;n[s.getAttribute("name")||""]=a(i(s,"value"))}for(var l,c=t(r(e,"SimpleData"));!(l=c()).done;){var f=l.value;n[f.getAttribute("name")||""]=a(f)}return n})}function K(e){return o(e,"TimeSpan",function(e){return{timespan:{begin:a(i(e,"begin")),end:a(i(e,"end"))}}})}function Q(e){return o(e,"TimeStamp",function(e){return{timestamp:a(i(e,"when"))}})}function X(e,t){return u(e,"styleUrl",function(e){return e=n(e),t[e]?Object.assign({styleUrl:e},t[e]):{styleUrl:e}})}function Y(e,t){var r,n=q(e),a=n.coordTimes,i={type:"Feature",geometry:(r=n.geometries,0===r.length?null:1===r.length?r[0]:{type:"GeometryCollection",geometries:r}),properties:Object.assign(c(e,["name","address","visibility","open","phoneNumber","description"]),X(e,t),D(e),J(e),K(e),Q(e),a.length?{coordinateProperties:{times:1===a.length?a[0]:a}}:{})},o=e.getAttribute("id");return null!==o&&""!==o&&(i.id=o),i}var Z=/*#__PURE__*/regeneratorRuntime.mark(ne);function ee(e){var t=e.getAttribute("id"),r=e.parentNode;return!t&&f(r)&&"CascadingStyle"===r.localName&&(t=r.getAttribute("kml:id")||r.getAttribute("id")),n(t||"")}function te(e){for(var a,i={},o=t(r(e,"Style"));!(a=o()).done;){var s=a.value;i[ee(s)]=D(s)}for(var l,c=function(){var e=l.value,t=n(e.getAttribute("id")||"");u(e,"styleUrl",function(e){e=n(e),i[e]&&(i[t]=i[e])})},f=t(r(e,"StyleMap"));!(l=f()).done;)c();return i}function re(e){var t=te(e),r={type:"root",children:[]};return function e(r,n){if(r.childNodes)for(var i=0;i<r.childNodes.length;i++)e(r.childNodes[i],n);if(f(r))switch(r.tagName){case"Placemark":var o=Y(r,t);o&&n.children.push(o);break;case"Folder":var u=function(e){for(var t=["name","visibility","open","address","description","phoneNumber","visibility"],r={},n=0,i=Array.from(e.childNodes);n<i.length;n++){var o=i[n];f(o)&&t.includes(o.tagName)&&(r[o.tagName]=a(o))}return{type:"folder",meta:r,children:[]}}(r);n.children.push(u),n=u}}(e,r),r}function ne(e){var n,a,i,o;return regeneratorRuntime.wrap(function(u){for(;;)switch(u.prev=u.next){case 0:n=te(e),a=t(r(e,"Placemark"));case 2:if((i=a()).done){u.next=10;break}if(!(o=Y(i.value,n))){u.next=8;break}return u.next=8,o;case 8:u.next=2;break;case 10:case"end":return u.stop()}},Z)}function ae(e){return{type:"FeatureCollection",features:Array.from(ne(e))}}export{S as gpx,A as gpxGen,ae as kml,ne as kmlGen,re as kmlWithFolders,M as tcx,L as tcxGen};
861
2
  //# sourceMappingURL=togeojson.es.js.map