Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): focus the journey or the flag that was clicked

Elian Doran74fdd6f21cc5
diff --git a/apps/client/src/services/gpx.ts b/apps/client/src/services/gpx.ts
index 83261ce212..3b82014600 100644
--- a/apps/client/src/services/gpx.ts
+++ b/apps/client/src/services/gpx.ts
@@ -1,7 +1,8 @@
/**
- * Reads a GPX file into the numbers a preview can show: how far it goes, how much it climbs, when
- * it was travelled and what it is made of. Pure parsing and arithmetic over the XML — nothing here
- * touches the map or the app, so the whole module is unit-testable.
+ * Reads a GPX file into the numbers a preview can show — how far it goes, how much it climbs, when
+ * it was travelled and what it is made of — and into the lines the map draws (see
+ * {@link readTrackLines}). Pure parsing and arithmetic over the XML — nothing here touches the map
+ * or the app, so the whole module is unit-testable.
*/
/** What marks a note as a GPX track: the mime its file carries. */
@@ -135,6 +136,67 @@ export function parseGpxStats(xml: string): GpxStats | null {
return stats;
}
+/** One of the journeys a GPX file holds — a `<trk>` or a `<rte>` — as the map draws it. */
+export interface GpxTrackLines {
+ /** What the file calls this track or route, where it names one. */
+ name?: string;
+ /** One line per segment of a track, kept apart where the recording stopped; a route is one line. */
+ lines: [number, number][][];
+}
+
+/**
+ * The lines a GPX file draws, one entry per track and one per route — a file may hold several, and
+ * each is a journey of its own: flagged, named and focused for itself (see GpxTrack and the pane's
+ * camera in DetailPane), where flattening them strung one journey's flags across another's ground.
+ *
+ * Points that name no readable position are dropped. A line of one point is kept: it draws nothing,
+ * but it is still where a journey began or ended, which is what the marks are placed from. A file
+ * whose points sit outside any track or route is not one the GPX schema allows, but it used to draw
+ * as a single line here and there is no reason to stop drawing it — the fallback is only reached
+ * when the reading above it found nothing, so a well-formed file never takes it.
+ */
+export function readTrackLines(doc: Document): GpxTrackLines[] {
+ const tracks: GpxTrackLines[] = [];
+
+ for (const container of doc.querySelectorAll("trk, rte")) {
+ const lines = container.localName === "rte"
+ ? [ readCoordinates(container.querySelectorAll("rtept")) ]
+ : [ ...container.querySelectorAll("trkseg") ].map((segment) => readCoordinates(segment.querySelectorAll("trkpt")));
+
+ const kept = lines.filter((line) => line.length > 0);
+ if (kept.length > 0) {
+ tracks.push({ name: childText(container, "name")?.trim() || undefined, lines: kept });
+ }
+ }
+
+ if (tracks.length === 0) {
+ const points = readCoordinates(doc.querySelectorAll("trkpt, rtept"));
+ if (points.length > 0) {
+ tracks.push({ lines: [ points ] });
+ }
+ }
+
+ return tracks;
+}
+
+/**
+ * The `[lng, lat]` GeoJSON wants, for each element that carries a readable pair. One that cannot
+ * say where it is is skipped rather than defaulted: falling back to zero put it in the Gulf of
+ * Guinea and ran the line out to it and back.
+ */
+export function readCoordinates(points: Iterable<Element>): [number, number][] {
+ const coordinates: [number, number][] = [];
+
+ for (const point of points) {
+ const lat = parseFloat(point.getAttribute("lat") ?? "");
+ const lon = parseFloat(point.getAttribute("lon") ?? "");
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+ coordinates.push([ lon, lat ]);
+ }
+
+ return coordinates;
+}
+
/** How much a point's elevation must move, in metres, before it counts as climbing rather than as
* the few metres of jitter GPS elevation always carries. */
const ELEVATION_NOISE_M = 5;
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
index ed1ff848c4..a5f0b288e0 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
@@ -124,9 +124,10 @@ function markerFeature(note: FNote, coordinates: [number, number] = [ 2, 1 ]) {
return { geometry: { type: "Point", coordinates }, properties: { id: note.noteId } };
}
-/** A GPX track's hit line, as MapLibre reports one — the note carried in the feature (see GpxTrack). */
-function trackFeature(note: FNote) {
- return { geometry: { type: "MultiLineString", coordinates: [] }, properties: { id: note.noteId } };
+/** A GPX track's hit line, as MapLibre reports one — the note carried in the feature (see GpxTrack),
+ * and which of the file's journeys the line is, where the source says. */
+function trackFeature(note: FNote, track?: number) {
+ return { geometry: { type: "MultiLineString", coordinates: [] }, properties: { id: note.noteId, ...(track !== undefined ? { track } : {}) } };
}
describe("DetailPane", () => {
@@ -320,6 +321,60 @@ describe("DetailPane", () => {
expect(map.fitted).toHaveLength(1);
});
+ /**
+ * A file may hold several journeys, and the clicked line says which it is (the `track` index,
+ * see GpxTrack): only that one is framed. The other journey's ground — and a waypoint hung off
+ * in a third place — is exactly what focusing one track is meant to leave out of the frame.
+ */
+ it("fits only the journey that was clicked, of a file holding several", async () => {
+ buildNote({ id: "root", title: "root", children: [ { id: "hiketwo", title: "Two rides", mime: GPX_MIME } ] });
+ const note = froca.notes["hiketwo"];
+ const map = fakeMap();
+ map.addSource(trackSourceId(note.noteId), {
+ type: "FeatureCollection",
+ features: [
+ { type: "Feature", properties: { id: note.noteId, track: 0 }, geometry: { type: "MultiLineString", coordinates: [ [ [ 24.13, 45.79 ], [ 24.16, 45.96 ] ] ] } },
+ { type: "Feature", properties: { id: note.noteId, track: 1 }, geometry: { type: "MultiLineString", coordinates: [ [ [ 25.5, 46.5 ], [ 25.7, 46.7 ] ] ] } },
+ { type: "Feature", properties: { id: note.noteId }, geometry: { type: "Point", coordinates: [ 20, 40 ] } }
+ ]
+ });
+ await mount([ note ], map);
+
+ map.setUnderPointer([ trackFeature(note, 1) ]);
+ await act(async () => map.click());
+ await settle();
+
+ expect(map.fitted).toEqual([ {
+ bounds: [ [ 25.5, 46.5 ], [ 25.7, 46.7 ] ],
+ options: { padding: { top: 60, bottom: 60, left: 60, right: 460 }, maxZoom: 16 }
+ } ]);
+ });
+
+ /**
+ * A clicked flag is a place the reader chose, not a request to re-frame the file: it is stood
+ * clear of the pane at the zoom they were reading at, exactly as a note marker is — flying out
+ * to the whole track would lose the very flag they clicked.
+ */
+ it("pans to a clicked flag without re-framing the whole file", async () => {
+ buildNote({ id: "root", title: "root", children: [ { id: "hikeflag", title: "A hike", mime: GPX_MIME } ] });
+ const note = froca.notes["hikeflag"];
+ const map = fakeMap();
+ map.addSource(trackSourceId(note.noteId), {
+ type: "FeatureCollection",
+ features: [ { type: "Feature", properties: { id: note.noteId }, geometry: { type: "MultiLineString", coordinates: [ [ [ 24.13, 45.79 ], [ 24.16, 45.96 ] ] ] } } ]
+ });
+ await mount([ note ], map);
+
+ // The click lands on one of the track's marks — a Point feature, the same shape a note's
+ // pin answers a hit with.
+ map.setUnderPointer([ markerFeature(note, [ 24.16, 45.96 ]) ]);
+ await act(async () => map.click());
+ await settle();
+
+ expect(map.fitted).toEqual([]);
+ expect(map.eased).toEqual([ { center: [ 24.16, 45.96 ], offset: [ -200, 0 ] } ]);
+ });
+
/**
* Regression test for a click on a marker whiting out the map and losing its WebGL context.
*
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
index cab77fbf4e..292ded75a2 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
@@ -1,7 +1,7 @@
import "./DetailPane.css";
import clsx from "clsx";
-import type { GeoJSONSource, Map as MapLibreGLMap, MapMouseEvent, MapSourceDataEvent } from "maplibre-gl";
+import type { GeoJSONSource, MapGeoJSONFeature, Map as MapLibreGLMap, MapMouseEvent, MapSourceDataEvent } from "maplibre-gl";
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
import appContext from "../../../components/app_context";
@@ -39,8 +39,21 @@ export interface PaneSelection {
/** Created a moment ago, so the pane opens with the stock title selected, ready to be typed
* over — the note has no name yet worth protecting from a keystroke. */
isNew?: boolean;
+ /** What of the note the click named, where it named more than the note. See {@link PaneFocus}. */
+ focus?: PaneFocus;
}
+/**
+ * What of a GPX note the camera should honour, a file being more than one thing to point at: a flag
+ * clicked is a place, stood clear of the pane at the zoom the reader chose; one of the file's
+ * tracks clicked is a shape, fitted whole. Absent — the note opened without a click saying more,
+ * or a click on the line of a file that holds only one journey's worth — the whole file is fitted.
+ * Camera only: the pane shows the note either way.
+ */
+export type PaneFocus =
+ | { at: [ number, number ] }
+ | { track: number };
+
/**
* The pane standing against the trailing edge of the map for as long as a marker is selected.
*
@@ -134,7 +147,7 @@ export default function DetailPane({ notes, placing, isReadOnly, selection, onSe
return;
}
- onSelect({ noteId: String(feature.properties.id) });
+ onSelect({ noteId: String(feature.properties.id), focus: featureFocus(feature) });
};
map.on("click", onClick);
@@ -147,11 +160,22 @@ export default function DetailPane({ notes, placing, isReadOnly, selection, onSe
// location too, so a marker that has just been put somewhere else is followed there.
//
// A GPX track is not a point but a shape, so it is fitted rather than centred: panned and
- // zoomed until the whole of it stands in the part of the map the pane leaves uncovered.
+ // zoomed until it stands in the part of the map the pane leaves uncovered — the whole file,
+ // or only what the click named where it named more (see PaneFocus).
useEffect(() => {
if (!map || !note) return;
if (note.mime === GPX_MIME) {
+ const focus = selection?.focus;
+
+ // A clicked flag is a place the reader chose: stood clear of the pane at the zoom they
+ // were reading at, exactly as a note marker is — flying out to frame the whole file
+ // would lose the very flag they clicked.
+ if (focus && "at" in focus) {
+ map.easeTo({ center: focus.at, offset: paneOffset(map) });
+ return;
+ }
+
const sourceId = trackSourceId(note.noteId);
// Reading the track back off the map is asynchronous, and the answer may arrive after
// the pane has moved on — to another note, or to nothing at all — or after another
@@ -159,7 +183,7 @@ export default function DetailPane({ notes, placing, isReadOnly, selection, onSe
let done = false;
const fit = async () => {
- const bounds = await trackBounds(map, note.noteId);
+ const bounds = await trackBounds(map, note.noteId, focus?.track);
if (done || !bounds) return;
done = true;
map.off("sourcedata", onSourceData);
@@ -187,7 +211,9 @@ export default function DetailPane({ notes, placing, isReadOnly, selection, onSe
if (!coordinates) return;
map.easeTo({ center: coordinates, offset: paneOffset(map) });
- }, [ map, note?.noteId, location ]);
+ // The focus is depended on by identity, which a click renews even on the same note: every
+ // click is a fresh ask, and re-clicking what is already open brings it back into view.
+ }, [ map, note?.noteId, location, selection?.focus ]);
// Bound only while something is selected, so the map's other Escape — giving up on placing a
// marker (see index.tsx) — stands alone when nothing is.
@@ -282,12 +308,33 @@ const TRACK_FIT_AIR = 60;
* neighbourhood, not of somebody's garden. */
const TRACK_FIT_MAX_ZOOM = 16;
+/**
+ * What of its note a clicked feature names, beyond the note itself: its own place, for a point (a
+ * track's flag or a note's pin), or which of a file's journeys it is, for a line that says
+ * (`track`, see GpxTrack). A line's extent cannot be read here — the geometry a rendered feature
+ * answers with is clipped to the tile it was hit in — so a track is named for the camera effect to
+ * measure off the source instead. A note marker's point is named too, and goes unused: its camera
+ * follows the location label, which also moves when the marker does (see the camera effect).
+ */
+function featureFocus(feature: MapGeoJSONFeature): PaneFocus | undefined {
+ if (feature.geometry.type === "Point") {
+ return { at: feature.geometry.coordinates as [ number, number ] };
+ }
+
+ const track = feature.properties?.track;
+ return typeof track === "number" ? { track } : undefined;
+}
+
/**
* The corners of the selected track, as `fitBounds` wants them, read back off the map itself — the
- * source already holds every point of the line and its marks, so the file is not parsed twice.
+ * source already holds every point of the lines and their marks, so the file is not parsed twice.
* `null` for a track that is not on this map, or holds nothing with a place.
+ *
+ * Given a `track`, only the journey under that index counts (see the `track` property in GpxTrack):
+ * its flags stand on its line, and another journey's ground — or a waypoint hung off in a third
+ * place — is exactly what focusing one track is meant to leave out of frame.
*/
-async function trackBounds(map: MapLibreGLMap, noteId: string): Promise<[[number, number], [number, number]] | null> {
+async function trackBounds(map: MapLibreGLMap, noteId: string, track?: number): Promise<[[number, number], [number, number]] | null> {
const data = await map.getSource<GeoJSONSource>(trackSourceId(noteId))?.getData();
if (!data || data.type !== "FeatureCollection") return null;
@@ -299,7 +346,9 @@ async function trackBounds(map: MapLibreGLMap, noteId: string): Promise<[[number
north = Math.max(north, lat);
};
- for (const { geometry } of data.features) {
+ for (const { geometry, properties } of data.features) {
+ if (track !== undefined && properties?.track !== track) continue;
+
if (geometry.type === "Point") {
extend(geometry.coordinates);
} else if (geometry.type === "MultiLineString") {
diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx
index df31485594..267b63e8b2 100644
--- a/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx
@@ -306,6 +306,44 @@ describe("GpxTrack", () => {
}
});
+ /**
+ * A file may hold several tracks, and each is a journey of its own: a line of its own — named
+ * by the feature's `track` index, which is how a click on one says which it hit (see the pane's
+ * focus in DetailPane) — flagged with its own start and end, and labelled with its own name
+ * where the file gives one. One pair of flags strung across the file marked a start in one town
+ * and an end in another as though something ran between.
+ */
+ it("draws each of the file's tracks as a journey of its own", () => {
+ map.loadStyle();
+ renderTrack({
+ styleLoaded: true,
+ gpx: `<?xml version="1.0" encoding="UTF-8"?>
+<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">
+ <trk><name>Day one</name><trkseg>
+ <trkpt lat="45.79" lon="24.13" /><trkpt lat="45.81" lon="24.14" />
+ </trkseg></trk>
+ <trk><trkseg>
+ <trkpt lat="46.20" lon="24.50" /><trkpt lat="46.30" lon="24.60" />
+ </trkseg></trk>
+</gpx>`
+ });
+
+ const lines = features().filter((feature) => feature.geometry.type === "MultiLineString");
+ expect(lines.map((line) => line.properties)).toEqual([
+ // Named for itself where the file names it, for the note where it does not.
+ { id: NOTE_ID, track: 0, name: "Day one" },
+ { id: NOTE_ID, track: 1, name: "A Sunday ride" }
+ ]);
+
+ // A pair of flags per journey, the start of each saying its own name.
+ expect(marks().map((mark) => ({ ...mark.properties, at: mark.geometry.coordinates }))).toEqual([
+ { id: NOTE_ID, icon: START_IMAGE, name: "Day one", at: [ 24.13, 45.79 ] },
+ { id: NOTE_ID, icon: END_IMAGE, name: "", at: [ 24.14, 45.81 ] },
+ { id: NOTE_ID, icon: START_IMAGE, name: "A Sunday ride", at: [ 24.5, 46.2 ] },
+ { id: NOTE_ID, icon: END_IMAGE, name: "", at: [ 24.6, 46.3 ] }
+ ]);
+ });
+
it("draws a route as it draws a track", () => {
map.loadStyle();
renderTrack({
@@ -362,7 +400,7 @@ describe("GpxTrack", () => {
expect(label?.layout?.["symbol-placement"]).toBe("line");
expect(label?.layout?.["text-field"]).toEqual([ "get", "name" ]);
expect(label?.layout?.["text-font"]).toEqual([ "Open Sans Regular" ]);
- expect(trackProperties()).toEqual({ id: NOTE_ID, name: "A Sunday ride" });
+ expect(trackProperties()).toEqual({ id: NOTE_ID, track: 0, name: "A Sunday ride" });
});
it("draws the name the way the marker titles are drawn, light map or dark", () => {
diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
index a9cc2192d9..56bd0e2511 100644
--- a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
@@ -1,7 +1,7 @@
import type { FilterSpecification, Map as MapLibreGLMap } from "maplibre-gl";
import { useContext, useEffect } from "preact/hooks";
-import { childText, GPX_MIME } from "../../../services/gpx";
+import { childText, GPX_MIME, type GpxTrackLines, readCoordinates, readTrackLines } from "../../../services/gpx";
import { MapStyleLoaded, ParentMap } from "./map";
import { buildMarkerImage, LABEL_LAYOUT, LABEL_PAINT, MARKER_SHADOW_PADDING, markerImageId } from "./Markers";
@@ -92,8 +92,8 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, pinColor, ic
const marksLayerId = `${MARKS_LAYER_PREFIX}${noteId}`;
const gpxDoc = new DOMParser().parseFromString(gpxXmlString, "application/xml");
- const lines = readLines(gpxDoc);
- const marks = readMarks(gpxDoc, lines, { noteId, title, pinColor, iconClass });
+ const tracks = readTrackLines(gpxDoc);
+ const marks = readMarks(gpxDoc, tracks, { noteId, title, pinColor, iconClass });
// The pins the marks stamp, rasterized off this path: the line must not wait on them, so
// the layers go up in two halves — the line at once, the marks when their images arrive.
@@ -109,7 +109,7 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, pinColor, ic
// would never draw it. Failing is expected in that window — the style load that follows
// calls this again, against a style that will have it.
function addTrackLayers() {
- if (lines.length === 0 && marks.length === 0) return;
+ if (tracks.length === 0 && marks.length === 0) return;
try {
if (!map.getSource(sourceId)) {
@@ -118,29 +118,34 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, pinColor, ic
data: {
type: "FeatureCollection",
features: [
- // One line per segment rather than every point strung together: a
- // track is broken into segments exactly where it stopped being
- // recorded, so joining them drew a straight line across each gap.
+ // A line per track or route the file holds, each of its segments
+ // kept apart rather than strung together: a track is broken into
+ // segments exactly where it stopped being recorded, so joining
+ // them drew a straight line across each gap.
//
- // The note the line stands for is carried by the feature, so that
+ // The note a line stands for is carried by the feature, so that
// whatever the pointer lands on can be traced back to it — `id` is
- // what a click or the context menu opens, and `name` is what the
- // line is labelled with. The marks carry the same (see readMarks).
- ...(lines.length > 0 ? [ {
+ // what a click or the context menu opens, `track` says which of
+ // the file's journeys was hit so the camera can frame that one
+ // alone (see the pane's focus in DetailPane), and `name` is what
+ // the line is labelled with: the track's own where the file gives
+ // one, the note's title where it does not. The marks carry the
+ // same id (see readMarks).
+ ...tracks.map((track, index) => ({
type: "Feature",
- properties: { id: noteId, name: title },
+ properties: { id: noteId, track: index, name: track.name ?? title },
geometry: {
type: "MultiLineString",
- coordinates: lines
+ coordinates: track.lines
}
- } satisfies GeoJSON.Feature ] : []),
+ } satisfies GeoJSON.Feature)),
...marks
]
}
});
}
- if (lines.length > 0) {
+ if (tracks.length > 0) {
if (!map.getLayer(layerId)) {
map.addLayer({
id: layerId,
@@ -318,14 +323,17 @@ export function trackHitLayers(map: MapLibreGLMap) {
}
/**
- * The marks a track is flagged with, as features of the same source its line is drawn from: where
- * the whole track begins and where it ends — not one pair per segment, since a track broken into
- * segments is still one journey, and a flag at every pause would be a flag at every traffic light —
- * and one at every waypoint. The start says the note's name and a waypoint its own `<name>` — a
- * file like the GPX spec's own sample carries dozens of named crossings, and a pin that will not
- * say which one it is answers only to a click; the end's pin says the rest.
+ * The marks a file is flagged with, as features of the same source its lines are drawn from: where
+ * each of its tracks begins and ends — a pair per journey rather than per segment, since a track
+ * broken into segments is still one journey and a flag at every pause would be a flag at every
+ * traffic light; but a file of several tracks is several journeys, and one pair strung across them
+ * flagged a start in one town and an end in another as though something ran between — and one mark
+ * at every waypoint. A start says its track's name (the note's, for a track the file left nameless)
+ * and a waypoint its own `<name>` — a file like the GPX spec's own sample carries dozens of named
+ * crossings, and a pin that will not say which one it is answers only to a click; the ends' pin
+ * says the rest.
*/
-function readMarks(gpxDoc: Document, lines: [number, number][][], { noteId, title, pinColor, iconClass }: {
+function readMarks(gpxDoc: Document, tracks: GpxTrackLines[], { noteId, title, pinColor, iconClass }: {
noteId: string; title: string; pinColor: string; iconClass: string;
}) {
const marks: GeoJSON.Feature[] = [];
@@ -338,11 +346,12 @@ function readMarks(gpxDoc: Document, lines: [number, number][][], { noteId, titl
});
}
- const firstLine = lines[0] ?? [];
- const lastLine = lines[lines.length - 1] ?? [];
+ for (const track of tracks) {
+ const firstLine = track.lines[0] ?? [];
+ const lastLine = track.lines[track.lines.length - 1] ?? [];
+ if (firstLine.length === 0) continue;
- if (firstLine.length > 0) {
- addMark(firstLine[0], iconClass, title);
+ addMark(firstLine[0], iconClass, track.name ?? title);
const end = lastLine[lastLine.length - 1];
if (end && end !== firstLine[0]) {
addMark(end, END_ICON);
@@ -350,7 +359,7 @@ function readMarks(gpxDoc: Document, lines: [number, number][][], { noteId, titl
}
for (const waypoint of gpxDoc.querySelectorAll("wpt")) {
- const [ coordinates ] = readPoints([ waypoint ]);
+ const [ coordinates ] = readCoordinates([ waypoint ]);
if (coordinates) {
addMark(coordinates, WAYPOINT_ICON, childText(waypoint, "name")?.trim() ?? "");
}
@@ -378,51 +387,3 @@ async function buildMarkImages(pinColor: string, iconClass: string) {
return images;
}
-/**
- * The lines a GPX file draws, one per track segment and one per route.
- *
- * A track is split into segments precisely where the recording stopped and picked up again — a lost
- * signal, a paused watch, a drive home nobody logged — so the segments are kept apart rather than
- * strung together. Routes are lines of the same kind and are read alongside them.
- *
- * Points that name no readable position are dropped. A line of one point is kept: it draws nothing,
- * but it is still where the track began or ended, which is what the marks are placed from.
- */
-function readLines(gpxDoc: Document): [number, number][][] {
- const lines: [number, number][][] = [];
-
- for (const container of gpxDoc.querySelectorAll("trkseg, rte")) {
- const points = readPoints(container.querySelectorAll("trkpt, rtept"));
- if (points.length > 0) {
- lines.push(points);
- }
- }
-
- // A file whose points sit outside any segment or route is not one the GPX schema allows, but it
- // used to draw as a single line here and there is no reason to stop drawing it. Only reached when
- // the reading above found nothing, so a well-formed file never takes this path.
- if (lines.length === 0) {
- const points = readPoints(gpxDoc.querySelectorAll("trkpt, rtept"));
- if (points.length > 0) {
- lines.push(points);
- }
- }
-
- return lines;
-}
-
-/** The `[lng, lat]` GeoJSON wants, for each point that carries a readable pair. */
-function readPoints(points: Iterable<Element>): [number, number][] {
- const coordinates: [number, number][] = [];
-
- for (const point of points) {
- const lat = parseFloat(point.getAttribute("lat") ?? "");
- const lon = parseFloat(point.getAttribute("lon") ?? "");
- // A point that cannot say where it is is skipped rather than defaulted: falling back to zero
- // put it in the Gulf of Guinea and ran the line out to it and back.
- if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
- coordinates.push([ lon, lat ]);
- }
-
- return coordinates;
-}