Fix distance calculation for GPX files without elevation data

Distance was only stored in the elevation profile array, which was
empty when track points had no <ele> elements. Now computed via
haversine independently and exposed as gpxData.distance.

Tested: berlin-dresden-radweg-2021.gpx (5660 points, no elevation)
now correctly reports 248.8 km.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-04-02 20:19:55 +01:00
parent ed2d04c248
commit d5bcecb345
No known key found for this signature in database
GPG key ID: A32FF691A0F752D9
4 changed files with 8 additions and 11 deletions

View file

@ -46,9 +46,9 @@ function parseGpxWithParser(parser: DOMParser, xml: string): GpxData {
const name = doc.querySelector("metadata > name")?.textContent ?? undefined;
const waypoints = parseWaypoints(doc);
const tracks = parseTracks(doc);
const elevation = computeElevation(tracks);
const { totalDistance, ...elevation } = computeElevation(tracks);
return { name, waypoints, tracks, elevation };
return { name, waypoints, tracks, distance: totalDistance, elevation };
}
function parseWaypoints(doc: Document): Waypoint[] {
@ -85,7 +85,7 @@ function parseTracks(doc: Document): TrackPoint[][] {
return tracks;
}
function computeElevation(tracks: TrackPoint[][]): GpxData["elevation"] {
function computeElevation(tracks: TrackPoint[][]): GpxData["elevation"] & { totalDistance: number } {
let gain = 0;
let loss = 0;
const profile: ElevationProfile[] = [];
@ -112,7 +112,7 @@ function computeElevation(tracks: TrackPoint[][]): GpxData["elevation"] {
}
}
return { gain: Math.round(gain), loss: Math.round(loss), profile };
return { totalDistance: Math.round(totalDistance), gain: Math.round(gain), loss: Math.round(loss), profile };
}
/** Haversine distance between two points in meters */

View file

@ -18,6 +18,8 @@ export interface GpxData {
name?: string;
waypoints: Waypoint[];
tracks: TrackPoint[][];
/** Total distance in meters (haversine, works with or without elevation data) */
distance: number;
elevation: {
gain: number;
loss: number;