@tmcw/togeojson 4.7.0 → 5.0.0-1

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