@tmcw/togeojson 5.0.0 → 5.1.3-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.
@@ -0,0 +1,927 @@
1
+ function $(element, tagName) {
2
+ return Array.from(element.getElementsByTagName(tagName));
3
+ }
4
+ function normalizeId(id) {
5
+ return id[0] === "#" ? id : `#${id}`;
6
+ }
7
+ function $ns(element, tagName, ns) {
8
+ return Array.from(element.getElementsByTagNameNS(ns, tagName));
9
+ }
10
+ /**
11
+ * get the content of a text node, if any
12
+ */
13
+ function nodeVal(node) {
14
+ node?.normalize();
15
+ return (node && node.textContent) || "";
16
+ }
17
+ /**
18
+ * Get one Y child of X, if any, otherwise null
19
+ */
20
+ function get1(node, tagName, callback) {
21
+ const n = node.getElementsByTagName(tagName);
22
+ const result = n.length ? n[0] : null;
23
+ if (result && callback)
24
+ callback(result);
25
+ return result;
26
+ }
27
+ function get(node, tagName, callback) {
28
+ const properties = {};
29
+ if (!node)
30
+ return properties;
31
+ const n = node.getElementsByTagName(tagName);
32
+ const result = n.length ? n[0] : null;
33
+ if (result && callback) {
34
+ return callback(result, properties);
35
+ }
36
+ return properties;
37
+ }
38
+ function val1(node, tagName, callback) {
39
+ const val = nodeVal(get1(node, tagName));
40
+ if (val && callback)
41
+ return callback(val) || {};
42
+ return {};
43
+ }
44
+ function $num(node, tagName, callback) {
45
+ const val = parseFloat(nodeVal(get1(node, tagName)));
46
+ if (isNaN(val))
47
+ return undefined;
48
+ if (val && callback)
49
+ return callback(val) || {};
50
+ return {};
51
+ }
52
+ function num1(node, tagName, callback) {
53
+ const val = parseFloat(nodeVal(get1(node, tagName)));
54
+ if (isNaN(val))
55
+ return undefined;
56
+ if (val && callback)
57
+ callback(val);
58
+ return val;
59
+ }
60
+ function getMulti(node, propertyNames) {
61
+ const properties = {};
62
+ for (const property of propertyNames) {
63
+ val1(node, property, (val) => {
64
+ properties[property] = val;
65
+ });
66
+ }
67
+ return properties;
68
+ }
69
+ function isElement(node) {
70
+ return node?.nodeType === 1;
71
+ }
72
+
73
+ function getLineStyle(node) {
74
+ return get(node, "line", (lineStyle) => {
75
+ const val = Object.assign({}, val1(lineStyle, "color", (color) => {
76
+ return { stroke: `#${color}` };
77
+ }), $num(lineStyle, "opacity", (opacity) => {
78
+ return { "stroke-opacity": opacity };
79
+ }), $num(lineStyle, "width", (width) => {
80
+ // GPX width is in mm, convert to px with 96 px per inch
81
+ return { "stroke-width": (width * 96) / 25.4 };
82
+ }));
83
+ return val;
84
+ });
85
+ }
86
+
87
+ function getExtensions(node) {
88
+ let values = [];
89
+ if (node === null)
90
+ return values;
91
+ for (const child of Array.from(node.childNodes)) {
92
+ if (!isElement(child))
93
+ continue;
94
+ const name = abbreviateName(child.nodeName);
95
+ if (name === "gpxtpx:TrackPointExtension") {
96
+ // loop again for nested garmin extensions (eg. "gpxtpx:hr")
97
+ values = values.concat(getExtensions(child));
98
+ }
99
+ else {
100
+ // push custom extension (eg. "power")
101
+ const val = nodeVal(child);
102
+ values.push([name, parseNumeric(val)]);
103
+ }
104
+ }
105
+ return values;
106
+ }
107
+ function abbreviateName(name) {
108
+ return ["heart", "gpxtpx:hr", "hr"].includes(name) ? "heart" : name;
109
+ }
110
+ function parseNumeric(val) {
111
+ const num = parseFloat(val);
112
+ return isNaN(num) ? val : num;
113
+ }
114
+
115
+ function coordPair$1(node) {
116
+ const ll = [
117
+ parseFloat(node.getAttribute("lon") || ""),
118
+ parseFloat(node.getAttribute("lat") || ""),
119
+ ];
120
+ if (isNaN(ll[0]) || isNaN(ll[1])) {
121
+ return null;
122
+ }
123
+ num1(node, "ele", (val) => {
124
+ ll.push(val);
125
+ });
126
+ const time = get1(node, "time");
127
+ return {
128
+ coordinates: ll,
129
+ time: time ? nodeVal(time) : null,
130
+ extendedValues: getExtensions(get1(node, "extensions")),
131
+ };
132
+ }
133
+
134
+ function extractProperties(node) {
135
+ const properties = getMulti(node, [
136
+ "name",
137
+ "cmt",
138
+ "desc",
139
+ "type",
140
+ "time",
141
+ "keywords",
142
+ ]);
143
+ const extensions = Array.from(node.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3", "*"));
144
+ for (const child of extensions) {
145
+ if (child.parentNode?.parentNode === node) {
146
+ properties[child.tagName.replace(":", "_")] = nodeVal(child);
147
+ }
148
+ }
149
+ const links = $(node, "link");
150
+ if (links.length) {
151
+ properties.links = links.map((link) => Object.assign({ href: link.getAttribute("href") }, getMulti(link, ["text", "type"])));
152
+ }
153
+ return properties;
154
+ }
155
+
156
+ /**
157
+ * Extract points from a trkseg or rte element.
158
+ */
159
+ function getPoints$1(node, pointname) {
160
+ const pts = $(node, pointname);
161
+ const line = [];
162
+ const times = [];
163
+ const extendedValues = {};
164
+ for (let i = 0; i < pts.length; i++) {
165
+ const c = coordPair$1(pts[i]);
166
+ if (!c) {
167
+ continue;
168
+ }
169
+ line.push(c.coordinates);
170
+ if (c.time)
171
+ times.push(c.time);
172
+ for (const [name, val] of c.extendedValues) {
173
+ const plural = name === "heart" ? name : name.replace("gpxtpx:", "") + "s";
174
+ if (!extendedValues[plural]) {
175
+ extendedValues[plural] = Array(pts.length).fill(null);
176
+ }
177
+ extendedValues[plural][i] = val;
178
+ }
179
+ }
180
+ if (line.length < 2)
181
+ return; // Invalid line in GeoJSON
182
+ return {
183
+ line: line,
184
+ times: times,
185
+ extendedValues: extendedValues,
186
+ };
187
+ }
188
+ /**
189
+ * Extract a LineString geometry from a rte
190
+ * element.
191
+ */
192
+ function getRoute(node) {
193
+ const line = getPoints$1(node, "rtept");
194
+ if (!line)
195
+ return;
196
+ return {
197
+ type: "Feature",
198
+ properties: Object.assign({ _gpxType: "rte" }, extractProperties(node), getLineStyle(get1(node, "extensions"))),
199
+ geometry: {
200
+ type: "LineString",
201
+ coordinates: line.line,
202
+ },
203
+ };
204
+ }
205
+ function getTrack(node) {
206
+ const segments = $(node, "trkseg");
207
+ const track = [];
208
+ const times = [];
209
+ const extractedLines = [];
210
+ for (const segment of segments) {
211
+ const line = getPoints$1(segment, "trkpt");
212
+ if (line) {
213
+ extractedLines.push(line);
214
+ if (line.times && line.times.length)
215
+ times.push(line.times);
216
+ }
217
+ }
218
+ if (extractedLines.length === 0)
219
+ return null;
220
+ const multi = extractedLines.length > 1;
221
+ const properties = Object.assign({ _gpxType: "trk" }, extractProperties(node), getLineStyle(get1(node, "extensions")), times.length
222
+ ? {
223
+ coordinateProperties: {
224
+ times: multi ? times : times[0],
225
+ },
226
+ }
227
+ : {});
228
+ for (const line of extractedLines) {
229
+ track.push(line.line);
230
+ if (!properties.coordinateProperties) {
231
+ properties.coordinateProperties = {};
232
+ }
233
+ const props = properties.coordinateProperties;
234
+ const entries = Object.entries(line.extendedValues);
235
+ for (let i = 0; i < entries.length; i++) {
236
+ const [name, val] = entries[i];
237
+ if (multi) {
238
+ if (!props[name]) {
239
+ props[name] = extractedLines.map((line) => new Array(line.line.length).fill(null));
240
+ }
241
+ props[name][i] = val;
242
+ }
243
+ else {
244
+ props[name] = val;
245
+ }
246
+ }
247
+ }
248
+ return {
249
+ type: "Feature",
250
+ properties: properties,
251
+ geometry: multi
252
+ ? {
253
+ type: "MultiLineString",
254
+ coordinates: track,
255
+ }
256
+ : {
257
+ type: "LineString",
258
+ coordinates: track[0],
259
+ },
260
+ };
261
+ }
262
+ /**
263
+ * Extract a point, if possible, from a given node,
264
+ * which is usually a wpt or trkpt
265
+ */
266
+ function getPoint(node) {
267
+ const properties = Object.assign(extractProperties(node), getMulti(node, ["sym"]));
268
+ const pair = coordPair$1(node);
269
+ if (!pair)
270
+ return null;
271
+ return {
272
+ type: "Feature",
273
+ properties,
274
+ geometry: {
275
+ type: "Point",
276
+ coordinates: pair.coordinates,
277
+ },
278
+ };
279
+ }
280
+ /**
281
+ * Convert GPX to GeoJSON incrementally, returning
282
+ * a [Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
283
+ * that yields output feature by feature.
284
+ */
285
+ function* gpxGen(node) {
286
+ for (const track of $(node, "trk")) {
287
+ const feature = getTrack(track);
288
+ if (feature)
289
+ yield feature;
290
+ }
291
+ for (const route of $(node, "rte")) {
292
+ const feature = getRoute(route);
293
+ if (feature)
294
+ yield feature;
295
+ }
296
+ for (const waypoint of $(node, "wpt")) {
297
+ const point = getPoint(waypoint);
298
+ if (point)
299
+ yield point;
300
+ }
301
+ }
302
+ /**
303
+ *
304
+ * Convert a GPX document to GeoJSON. The first argument, `doc`, must be a GPX
305
+ * document as an XML DOM - not as a string. You can get this using jQuery's default
306
+ * `.ajax` function or using a bare XMLHttpRequest with the `.response` property
307
+ * holding an XML DOM.
308
+ *
309
+ * The output is a JavaScript object of GeoJSON data, same as `.kml` outputs, with the
310
+ * addition of a `_gpxType` property on each `LineString` feature that indicates whether
311
+ * the feature was encoded as a route (`rte`) or track (`trk`) in the GPX document.
312
+ */
313
+ function gpx(node) {
314
+ return {
315
+ type: "FeatureCollection",
316
+ features: Array.from(gpxGen(node)),
317
+ };
318
+ }
319
+
320
+ const EXTENSIONS_NS = "http://www.garmin.com/xmlschemas/ActivityExtension/v2";
321
+ const TRACKPOINT_ATTRIBUTES = [
322
+ ["heartRate", "heartRates"],
323
+ ["Cadence", "cadences"],
324
+ // Extended Trackpoint attributes
325
+ ["Speed", "speeds"],
326
+ ["Watts", "watts"],
327
+ ];
328
+ const LAP_ATTRIBUTES = [
329
+ ["TotalTimeSeconds", "totalTimeSeconds"],
330
+ ["DistanceMeters", "distanceMeters"],
331
+ ["MaximumSpeed", "maxSpeed"],
332
+ ["AverageHeartRateBpm", "avgHeartRate"],
333
+ ["MaximumHeartRateBpm", "maxHeartRate"],
334
+ // Extended Lap attributes
335
+ ["AvgSpeed", "avgSpeed"],
336
+ ["AvgWatts", "avgWatts"],
337
+ ["MaxWatts", "maxWatts"],
338
+ ];
339
+ function getProperties(node, attributeNames) {
340
+ const properties = [];
341
+ for (const [tag, alias] of attributeNames) {
342
+ let elem = get1(node, tag);
343
+ if (!elem) {
344
+ const elements = node.getElementsByTagNameNS(EXTENSIONS_NS, tag);
345
+ if (elements.length) {
346
+ elem = elements[0];
347
+ }
348
+ }
349
+ const val = parseFloat(nodeVal(elem));
350
+ if (!isNaN(val)) {
351
+ properties.push([alias, val]);
352
+ }
353
+ }
354
+ return properties;
355
+ }
356
+ function coordPair(node) {
357
+ const ll = [num1(node, "LongitudeDegrees"), num1(node, "LatitudeDegrees")];
358
+ if (ll[0] === undefined ||
359
+ isNaN(ll[0]) ||
360
+ ll[1] === undefined ||
361
+ isNaN(ll[1])) {
362
+ return null;
363
+ }
364
+ const heartRate = get1(node, "HeartRateBpm");
365
+ const time = nodeVal(get1(node, "Time"));
366
+ get1(node, "AltitudeMeters", (alt) => {
367
+ const a = parseFloat(nodeVal(alt));
368
+ if (!isNaN(a)) {
369
+ ll.push(a);
370
+ }
371
+ });
372
+ return {
373
+ coordinates: ll,
374
+ time: time || null,
375
+ heartRate: heartRate ? parseFloat(nodeVal(heartRate)) : null,
376
+ extensions: getProperties(node, TRACKPOINT_ATTRIBUTES),
377
+ };
378
+ }
379
+ function getPoints(node) {
380
+ const pts = $(node, "Trackpoint");
381
+ const line = [];
382
+ const times = [];
383
+ const heartRates = [];
384
+ if (pts.length < 2)
385
+ return null; // Invalid line in GeoJSON
386
+ const extendedProperties = {};
387
+ const result = { extendedProperties };
388
+ for (let i = 0; i < pts.length; i++) {
389
+ const c = coordPair(pts[i]);
390
+ if (c === null)
391
+ continue;
392
+ line.push(c.coordinates);
393
+ const { time, heartRate, extensions } = c;
394
+ if (time)
395
+ times.push(time);
396
+ if (heartRate)
397
+ heartRates.push(heartRate);
398
+ for (const [alias, value] of extensions) {
399
+ if (!extendedProperties[alias]) {
400
+ extendedProperties[alias] = Array(pts.length).fill(null);
401
+ }
402
+ extendedProperties[alias][i] = value;
403
+ }
404
+ }
405
+ if (line.length < 2)
406
+ return null;
407
+ return Object.assign(result, {
408
+ line: line,
409
+ times: times,
410
+ heartRates: heartRates,
411
+ });
412
+ }
413
+ function getLap(node) {
414
+ const segments = $(node, "Track");
415
+ const track = [];
416
+ const times = [];
417
+ const heartRates = [];
418
+ const allExtendedProperties = [];
419
+ let line;
420
+ const properties = Object.assign(Object.fromEntries(getProperties(node, LAP_ATTRIBUTES)), get(node, "Name", (nameElement) => {
421
+ return { name: nodeVal(nameElement) };
422
+ }));
423
+ for (const segment of segments) {
424
+ line = getPoints(segment);
425
+ if (line) {
426
+ track.push(line.line);
427
+ if (line.times.length)
428
+ times.push(line.times);
429
+ if (line.heartRates.length)
430
+ heartRates.push(line.heartRates);
431
+ allExtendedProperties.push(line.extendedProperties);
432
+ }
433
+ }
434
+ for (let i = 0; i < allExtendedProperties.length; i++) {
435
+ const extendedProperties = allExtendedProperties[i];
436
+ for (const property in extendedProperties) {
437
+ if (segments.length === 1) {
438
+ if (line) {
439
+ properties[property] = line.extendedProperties[property];
440
+ }
441
+ }
442
+ else {
443
+ if (!properties[property]) {
444
+ properties[property] = track.map((track) => Array(track.length).fill(null));
445
+ }
446
+ properties[property][i] = extendedProperties[property];
447
+ }
448
+ }
449
+ }
450
+ if (track.length === 0)
451
+ return null;
452
+ if (times.length || heartRates.length) {
453
+ properties.coordinateProperties = Object.assign(times.length
454
+ ? {
455
+ times: track.length === 1 ? times[0] : times,
456
+ }
457
+ : {}, heartRates.length
458
+ ? {
459
+ heart: track.length === 1 ? heartRates[0] : heartRates,
460
+ }
461
+ : {});
462
+ }
463
+ return {
464
+ type: "Feature",
465
+ properties: properties,
466
+ geometry: track.length === 1
467
+ ? {
468
+ type: "LineString",
469
+ coordinates: track[0],
470
+ }
471
+ : {
472
+ type: "MultiLineString",
473
+ coordinates: track,
474
+ },
475
+ };
476
+ }
477
+ /**
478
+ * Incrementally convert a TCX document to GeoJSON. The
479
+ * first argument, `doc`, must be a TCX
480
+ * document as an XML DOM - not as a string.
481
+ */
482
+ function* tcxGen(node) {
483
+ for (const lap of $(node, "Lap")) {
484
+ const feature = getLap(lap);
485
+ if (feature)
486
+ yield feature;
487
+ }
488
+ for (const course of $(node, "Courses")) {
489
+ const feature = getLap(course);
490
+ if (feature)
491
+ yield feature;
492
+ }
493
+ }
494
+ /**
495
+ * Convert a TCX document to GeoJSON. The first argument, `doc`, must be a TCX
496
+ * document as an XML DOM - not as a string.
497
+ */
498
+ function tcx(node) {
499
+ return {
500
+ type: "FeatureCollection",
501
+ features: Array.from(tcxGen(node)),
502
+ };
503
+ }
504
+
505
+ function fixColor(v, prefix) {
506
+ const properties = {};
507
+ const colorProp = prefix == "stroke" || prefix === "fill" ? prefix : prefix + "-color";
508
+ if (v[0] === "#") {
509
+ v = v.substring(1);
510
+ }
511
+ if (v.length === 6 || v.length === 3) {
512
+ properties[colorProp] = "#" + v;
513
+ }
514
+ else if (v.length === 8) {
515
+ properties[prefix + "-opacity"] = parseInt(v.substring(0, 2), 16) / 255;
516
+ properties[colorProp] =
517
+ "#" + v.substring(6, 8) + v.substring(4, 6) + v.substring(2, 4);
518
+ }
519
+ return properties;
520
+ }
521
+
522
+ function numericProperty(node, source, target) {
523
+ const properties = {};
524
+ num1(node, source, (val) => {
525
+ properties[target] = val;
526
+ });
527
+ return properties;
528
+ }
529
+ function getColor(node, output) {
530
+ return get(node, "color", (elem) => fixColor(nodeVal(elem), output));
531
+ }
532
+ function extractIcon(node) {
533
+ return get(node, "IconStyle", (iconStyle) => {
534
+ return Object.assign(getColor(iconStyle, "icon"), numericProperty(iconStyle, "scale", "icon-scale"), numericProperty(iconStyle, "heading", "icon-heading"), get(iconStyle, "hotSpot", (hotspot) => {
535
+ const left = parseFloat(hotspot.getAttribute("x") || "");
536
+ const top = parseFloat(hotspot.getAttribute("y") || "");
537
+ const xunits = hotspot.getAttribute("xunits") || "";
538
+ const yunits = hotspot.getAttribute("yunits") || "";
539
+ if (!isNaN(left) && !isNaN(top))
540
+ return {
541
+ "icon-offset": [left, top],
542
+ "icon-offset-units": [xunits, yunits],
543
+ };
544
+ return {};
545
+ }), get(iconStyle, "Icon", (icon, properties) => {
546
+ val1(icon, "href", (href) => {
547
+ properties.icon = href;
548
+ });
549
+ return properties;
550
+ }));
551
+ });
552
+ }
553
+ function extractLabel(node) {
554
+ return get(node, "LabelStyle", (labelStyle) => {
555
+ return Object.assign(getColor(labelStyle, "label"), numericProperty(labelStyle, "scale", "label-scale"));
556
+ });
557
+ }
558
+ function extractLine(node) {
559
+ return get(node, "LineStyle", (lineStyle) => {
560
+ return Object.assign(getColor(lineStyle, "stroke"), numericProperty(lineStyle, "width", "stroke-width"));
561
+ });
562
+ }
563
+ function extractPoly(node) {
564
+ return get(node, "PolyStyle", (polyStyle, properties) => {
565
+ return Object.assign(properties, get(polyStyle, "color", (elem) => fixColor(nodeVal(elem), "fill")), val1(polyStyle, "fill", (fill) => {
566
+ if (fill === "0")
567
+ return { "fill-opacity": 0 };
568
+ }), val1(polyStyle, "outline", (outline) => {
569
+ if (outline === "0")
570
+ return { "stroke-opacity": 0 };
571
+ }));
572
+ });
573
+ }
574
+ function extractStyle(node) {
575
+ return Object.assign({}, extractPoly(node), extractLine(node), extractLabel(node), extractIcon(node));
576
+ }
577
+
578
+ const removeSpace = /\s*/g;
579
+ const trimSpace = /^\s*|\s*$/g;
580
+ const splitSpace = /\s+/;
581
+ /**
582
+ * Get one coordinate from a coordinate array, if any
583
+ */
584
+ function coord1(value) {
585
+ return value
586
+ .replace(removeSpace, "")
587
+ .split(",")
588
+ .map(parseFloat)
589
+ .filter((num) => !isNaN(num));
590
+ }
591
+ /**
592
+ * Get all coordinates from a coordinate array as [[],[]]
593
+ */
594
+ function coord(value) {
595
+ return value
596
+ .replace(trimSpace, "")
597
+ .split(splitSpace)
598
+ .map(coord1)
599
+ .filter((coord) => {
600
+ return coord.length >= 2;
601
+ });
602
+ }
603
+ function gxCoords(node) {
604
+ let elems = $(node, "coord");
605
+ if (elems.length === 0) {
606
+ elems = $ns(node, "coord", "*");
607
+ }
608
+ const coordinates = elems.map((elem) => {
609
+ return nodeVal(elem).split(" ").map(parseFloat);
610
+ });
611
+ if (coordinates.length === 0) {
612
+ return null;
613
+ }
614
+ return {
615
+ geometry: coordinates.length > 2
616
+ ? {
617
+ type: "LineString",
618
+ coordinates,
619
+ }
620
+ : {
621
+ type: "Point",
622
+ coordinates: coordinates[0],
623
+ },
624
+ times: $(node, "when").map((elem) => nodeVal(elem)),
625
+ };
626
+ }
627
+ function fixRing(ring) {
628
+ if (ring.length === 0)
629
+ return ring;
630
+ const first = ring[0];
631
+ const last = ring[ring.length - 1];
632
+ let equal = true;
633
+ for (let i = 0; i < Math.max(first.length, last.length); i++) {
634
+ if (first[i] !== last[i]) {
635
+ equal = false;
636
+ break;
637
+ }
638
+ }
639
+ if (!equal) {
640
+ return ring.concat([ring[0]]);
641
+ }
642
+ return ring;
643
+ }
644
+ const GEO_TYPES = [
645
+ "Polygon",
646
+ "LineString",
647
+ "Point",
648
+ "Track",
649
+ "gx:Track",
650
+ ];
651
+ function getCoordinates(node) {
652
+ return nodeVal(get1(node, "coordinates"));
653
+ }
654
+ function getGeometry(node) {
655
+ const geometries = [];
656
+ const coordTimes = [];
657
+ for (const t of ["MultiGeometry", "MultiTrack", "gx:MultiTrack"]) {
658
+ const elem = get1(node, t);
659
+ if (elem) {
660
+ return getGeometry(elem);
661
+ }
662
+ }
663
+ for (const geoType of GEO_TYPES) {
664
+ for (const geomNode of $(node, geoType)) {
665
+ switch (geoType) {
666
+ case "Point": {
667
+ const coordinates = coord1(getCoordinates(geomNode));
668
+ if (coordinates.length >= 2) {
669
+ geometries.push({
670
+ type: "Point",
671
+ coordinates,
672
+ });
673
+ }
674
+ break;
675
+ }
676
+ case "LineString": {
677
+ const coordinates = coord(getCoordinates(geomNode));
678
+ if (coordinates.length >= 2) {
679
+ geometries.push({
680
+ type: "LineString",
681
+ coordinates,
682
+ });
683
+ }
684
+ break;
685
+ }
686
+ case "Polygon": {
687
+ const coords = [];
688
+ for (const linearRing of $(geomNode, "LinearRing")) {
689
+ const ring = fixRing(coord(getCoordinates(linearRing)));
690
+ if (ring.length >= 4) {
691
+ coords.push(ring);
692
+ }
693
+ }
694
+ if (coords.length) {
695
+ geometries.push({
696
+ type: "Polygon",
697
+ coordinates: coords,
698
+ });
699
+ }
700
+ break;
701
+ }
702
+ case "Track":
703
+ case "gx:Track": {
704
+ const gx = gxCoords(geomNode);
705
+ if (!gx)
706
+ break;
707
+ const { times, geometry } = gx;
708
+ geometries.push(geometry);
709
+ if (times.length)
710
+ coordTimes.push(times);
711
+ break;
712
+ }
713
+ }
714
+ }
715
+ }
716
+ return {
717
+ geometries,
718
+ coordTimes,
719
+ };
720
+ }
721
+
722
+ function extractExtendedData(node) {
723
+ return get(node, "ExtendedData", (extendedData, properties) => {
724
+ for (const data of $(extendedData, "Data")) {
725
+ properties[data.getAttribute("name") || ""] = nodeVal(get1(data, "value"));
726
+ }
727
+ for (const simpleData of $(extendedData, "SimpleData")) {
728
+ properties[simpleData.getAttribute("name") || ""] = nodeVal(simpleData);
729
+ }
730
+ return properties;
731
+ });
732
+ }
733
+ function geometryListToGeometry(geometries) {
734
+ return geometries.length === 0
735
+ ? null
736
+ : geometries.length === 1
737
+ ? geometries[0]
738
+ : {
739
+ type: "GeometryCollection",
740
+ geometries,
741
+ };
742
+ }
743
+ function extractTimeSpan(node) {
744
+ return get(node, "TimeSpan", (timeSpan) => {
745
+ return {
746
+ timespan: {
747
+ begin: nodeVal(get1(timeSpan, "begin")),
748
+ end: nodeVal(get1(timeSpan, "end")),
749
+ },
750
+ };
751
+ });
752
+ }
753
+ function extractTimeStamp(node) {
754
+ return get(node, "TimeStamp", (timeStamp) => {
755
+ return { timestamp: nodeVal(get1(timeStamp, "when")) };
756
+ });
757
+ }
758
+ function extractCascadedStyle(node, styleMap) {
759
+ return val1(node, "styleUrl", (styleUrl) => {
760
+ styleUrl = normalizeId(styleUrl);
761
+ if (styleMap[styleUrl]) {
762
+ return Object.assign({ styleUrl }, styleMap[styleUrl]);
763
+ }
764
+ // For backward-compatibility. Should we still include
765
+ // styleUrl even if it's not resolved?
766
+ return { styleUrl };
767
+ });
768
+ }
769
+ function getPlacemark(node, styleMap) {
770
+ const { coordTimes, geometries } = getGeometry(node);
771
+ const feature = {
772
+ type: "Feature",
773
+ geometry: geometryListToGeometry(geometries),
774
+ properties: Object.assign(getMulti(node, [
775
+ "name",
776
+ "address",
777
+ "visibility",
778
+ "open",
779
+ "phoneNumber",
780
+ "description",
781
+ ]), extractCascadedStyle(node, styleMap), extractStyle(node), extractExtendedData(node), extractTimeSpan(node), extractTimeStamp(node), coordTimes.length
782
+ ? {
783
+ coordinateProperties: {
784
+ times: coordTimes.length === 1 ? coordTimes[0] : coordTimes,
785
+ },
786
+ }
787
+ : {}),
788
+ };
789
+ const id = node.getAttribute("id");
790
+ if (id !== null && id !== "")
791
+ feature.id = id;
792
+ return feature;
793
+ }
794
+
795
+ function getStyleId(style) {
796
+ let id = style.getAttribute("id");
797
+ const parentNode = style.parentNode;
798
+ if (!id &&
799
+ isElement(parentNode) &&
800
+ parentNode.localName === "CascadingStyle") {
801
+ id = parentNode.getAttribute("kml:id") || parentNode.getAttribute("id");
802
+ }
803
+ return normalizeId(id || "");
804
+ }
805
+ function buildStyleMap(node) {
806
+ const styleMap = {};
807
+ for (const style of $(node, "Style")) {
808
+ styleMap[getStyleId(style)] = extractStyle(style);
809
+ }
810
+ for (const map of $(node, "StyleMap")) {
811
+ const id = normalizeId(map.getAttribute("id") || "");
812
+ val1(map, "styleUrl", (styleUrl) => {
813
+ styleUrl = normalizeId(styleUrl);
814
+ if (styleMap[styleUrl]) {
815
+ styleMap[id] = styleMap[styleUrl];
816
+ }
817
+ });
818
+ }
819
+ return styleMap;
820
+ }
821
+ const FOLDER_PROPS = [
822
+ "name",
823
+ "visibility",
824
+ "open",
825
+ "address",
826
+ "description",
827
+ "phoneNumber",
828
+ "visibility",
829
+ ];
830
+ function getFolder(node) {
831
+ const meta = {};
832
+ for (const child of Array.from(node.childNodes)) {
833
+ if (isElement(child) && FOLDER_PROPS.includes(child.tagName)) {
834
+ meta[child.tagName] = nodeVal(child);
835
+ }
836
+ }
837
+ return {
838
+ type: "folder",
839
+ meta,
840
+ children: [],
841
+ };
842
+ }
843
+ /**
844
+ * Yield a nested tree with KML folder structure
845
+ *
846
+ * This generates a tree with the given structure:
847
+ *
848
+ * ```js
849
+ * {
850
+ * "type": "root",
851
+ * "children": [
852
+ * {
853
+ * "type": "folder",
854
+ * "meta": {
855
+ * "name": "Test"
856
+ * },
857
+ * "children": [
858
+ * // ...features and folders
859
+ * ]
860
+ * }
861
+ * // ...features
862
+ * ]
863
+ * }
864
+ * ```
865
+ */
866
+ function kmlWithFolders(node) {
867
+ const styleMap = buildStyleMap(node);
868
+ const tree = { type: "root", children: [] };
869
+ function traverse(node, pointer) {
870
+ if (isElement(node)) {
871
+ switch (node.tagName) {
872
+ case "Placemark": {
873
+ const placemark = getPlacemark(node, styleMap);
874
+ if (placemark) {
875
+ pointer.children.push(placemark);
876
+ }
877
+ break;
878
+ }
879
+ case "Folder": {
880
+ const folder = getFolder(node);
881
+ pointer.children.push(folder);
882
+ pointer = folder;
883
+ break;
884
+ }
885
+ }
886
+ }
887
+ if (node.childNodes) {
888
+ for (let i = 0; i < node.childNodes.length; i++) {
889
+ traverse(node.childNodes[i], pointer);
890
+ }
891
+ }
892
+ }
893
+ traverse(node, tree);
894
+ return tree;
895
+ }
896
+ /**
897
+ * Convert KML to GeoJSON incrementally, returning
898
+ * a [Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
899
+ * that yields output feature by feature.
900
+ */
901
+ function* kmlGen(node) {
902
+ const styleMap = buildStyleMap(node);
903
+ for (const placemark of $(node, "Placemark")) {
904
+ const feature = getPlacemark(placemark, styleMap);
905
+ if (feature)
906
+ yield feature;
907
+ }
908
+ }
909
+ /**
910
+ * Convert a KML document to GeoJSON. The first argument, `doc`, must be a KML
911
+ * document as an XML DOM - not as a string. You can get this using jQuery's default
912
+ * `.ajax` function or using a bare XMLHttpRequest with the `.response` property
913
+ * holding an XML DOM.
914
+ *
915
+ * The output is a JavaScript object of GeoJSON data. You can convert it to a string
916
+ * with [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
917
+ * or use it directly in libraries.
918
+ */
919
+ function kml(node) {
920
+ return {
921
+ type: "FeatureCollection",
922
+ features: Array.from(kmlGen(node)),
923
+ };
924
+ }
925
+
926
+ export { gpx, gpxGen, kml, kmlGen, kmlWithFolders, tcx, tcxGen };
927
+ //# sourceMappingURL=togeojson.es.mjs.map