Files
gpx.studio/website/src/lib/components/toolbar/tools/routing/routing.ts
T

334 lines
11 KiB
TypeScript
Raw Normal View History

2026-10-11 11:18:36 +02:00
import { distance, type Coordinates } from '$lib/geo/coordinates';
import { settings } from '$lib/state/settings';
2025-02-02 11:17:22 +01:00
import { getElevation } from '$lib/utils';
2025-10-18 16:10:08 +02:00
import { get } from 'svelte/store';
2024-04-23 14:11:05 +02:00
2024-05-04 15:10:30 +02:00
const { routing, routingProfile, privateRoads } = settings;
2025-12-23 16:49:47 +01:00
export type RoutingProfile = {
engine: 'graphhopper' | 'brouter';
profile: string;
};
export const routingProfiles: { [key: string]: RoutingProfile } = {
bike: { engine: 'graphhopper', profile: 'bike' },
racing_bike: { engine: 'graphhopper', profile: 'racingbike' },
2026-01-17 11:58:47 +01:00
gravel_bike: { engine: 'graphhopper', profile: 'gravelbike' },
2025-12-23 16:49:47 +01:00
mountain_bike: { engine: 'graphhopper', profile: 'mtb' },
foot: { engine: 'graphhopper', profile: 'foot' },
2026-04-04 20:10:53 +02:00
motorcycle: { engine: 'graphhopper', profile: 'motorbike' },
2025-12-23 16:49:47 +01:00
water: { engine: 'brouter', profile: 'river' },
railway: { engine: 'brouter', profile: 'rail' },
2024-04-25 16:41:06 +02:00
};
2024-04-23 18:36:16 +02:00
2026-10-07 17:58:17 +02:00
/**
* The trackpoints of a route, as arrays with an entry per trackpoint. The OSM attributes are
* `undefined` where the router does not know them.
*/
export type RoutedPoints = {
lng: number[];
lat: number[];
ele: number[];
surface: (string | undefined)[];
highway: (string | undefined)[];
sacScale: (string | undefined)[];
mtbScale: (string | undefined)[];
};
2026-10-09 08:58:00 +02:00
export function emptyRoute(): RoutedPoints {
2026-10-07 17:58:17 +02:00
return { lng: [], lat: [], ele: [], surface: [], highway: [], sacScale: [], mtbScale: [] };
}
/** Adds a trackpoint, which has the elevation of the previous one if it has none. */
2026-10-09 08:58:00 +02:00
export function addPoint(route: RoutedPoints, lng: number, lat: number, ele: number | undefined) {
2026-10-07 17:58:17 +02:00
route.lng.push(lng);
route.lat.push(lat);
route.ele.push(ele ?? route.ele[route.ele.length - 1] ?? 0);
route.surface.push(undefined);
route.highway.push(undefined);
route.sacScale.push(undefined);
route.mtbScale.push(undefined);
}
export function route(points: Coordinates[]): Promise<RoutedPoints> {
2025-10-18 16:10:08 +02:00
if (get(routing)) {
2025-12-23 16:49:47 +01:00
const profile = routingProfiles[get(routingProfile)];
if (profile.engine === 'graphhopper') {
return getGraphHopperRoute(points, profile.profile, get(privateRoads));
} else {
return getBRouterRoute(points, profile.profile);
}
2024-04-23 18:36:16 +02:00
} else {
2024-05-09 00:02:27 +02:00
return getIntermediatePoints(points);
2024-04-23 18:36:16 +02:00
}
}
2025-12-23 16:49:47 +01:00
const graphhopperDetails = ['road_class', 'surface', 'hike_rating', 'mtb_rating'];
const hikeRatingToSACScale: { [key: string]: string } = {
'1': 'hiking',
'2': 'mountain_hiking',
'3': 'demanding_mountain_hiking',
'4': 'alpine_hiking',
'5': 'demanding_alpine_hiking',
'6': 'difficult_alpine_hiking',
};
const mtbRatingToScale: { [key: string]: string } = {
'1': '0',
'2': '1',
'3': '2',
'4': '3',
'5': '4',
'6': '5',
'7': '6',
};
2026-01-18 15:23:39 +01:00
2026-10-09 08:58:00 +02:00
export const graphhopperBlockPrivateCustomModels: { [key: string]: any } = {
2026-01-18 15:23:39 +01:00
bike: {
priority: [
{
if: 'bike_road_access == PRIVATE',
multiply_by: '0.0',
},
],
},
racingbike: {
priority: [
{
if: 'bike_road_access == PRIVATE',
multiply_by: '0.0',
},
],
},
gravelbike: {
priority: [
{
if: 'bike_road_access == PRIVATE',
multiply_by: '0.0',
},
],
},
mtb: {
priority: [
{
if: 'bike_road_access == PRIVATE',
multiply_by: '0.0',
},
],
},
foot: {
priority: [
{
if: 'foot_road_access == PRIVATE',
multiply_by: '0.0',
},
],
},
2026-10-09 08:58:00 +02:00
motorbike: {
2026-01-18 15:23:39 +01:00
priority: [
{
if: 'road_access == PRIVATE',
multiply_by: '0.0',
},
],
},
};
2025-12-23 16:49:47 +01:00
async function getGraphHopperRoute(
2025-02-02 11:17:22 +01:00
points: Coordinates[],
2025-12-23 16:49:47 +01:00
graphHopperProfile: string,
2025-02-02 11:17:22 +01:00
privateRoads: boolean
2026-10-07 17:58:17 +02:00
): Promise<RoutedPoints> {
2026-03-07 15:30:22 +01:00
let response = await fetch('https://graphhopper.gpx.studio/route', {
2025-12-23 16:49:47 +01:00
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
2026-10-08 18:34:19 +02:00
points: points.map((point) => [point.lng, point.lat]),
2025-12-23 16:49:47 +01:00
profile: graphHopperProfile,
elevation: true,
points_encoded: false,
details: graphhopperDetails,
custom_model: privateRoads
? {}
2026-01-18 15:23:39 +01:00
: graphhopperBlockPrivateCustomModels[graphHopperProfile] || {},
2025-12-23 16:49:47 +01:00
}),
});
if (!response.ok) {
2026-10-09 08:58:00 +02:00
throw graphHopperError(await response.json(), points.length);
2025-12-23 16:49:47 +01:00
}
2026-10-09 08:58:00 +02:00
return parseGraphHopperRoute(await response.json());
}
2025-12-23 16:49:47 +01:00
2026-10-09 08:58:00 +02:00
/** The error to throw for the error response of GraphHopper. Its message is a translation key. */
export function graphHopperError(
error: { message?: string; hints?: { details?: string }[] },
pointCount: number
): Error {
const message = error.message ?? '';
const details = error.hints?.[0]?.details ?? '';
if (message.includes('Cannot find point 0')) {
return new Error('toolbar.routing.error.from');
} else if (message.includes('Cannot find point 1')) {
return new Error(
pointCount == 3 ? 'toolbar.routing.error.via' : 'toolbar.routing.error.to'
);
} else if (details.includes('PointDistanceExceededException')) {
return new Error('toolbar.routing.error.distance');
} else if (details.includes('ConnectionNotFoundException')) {
return new Error('toolbar.routing.error.connection');
}
return new Error(message);
}
/**
* The route of a response of GraphHopper. The details of the path (road class, surface...) are
* given as ranges of points: `[from, to, value]`, `to` excluded except for the last range, which
* includes the last point.
*/
export function parseGraphHopperRoute(json: any): RoutedPoints {
2026-10-07 17:58:17 +02:00
const route = emptyRoute();
const coordinates = json.paths[0].points.coordinates;
const details = json.paths[0].details;
2025-12-23 16:49:47 +01:00
for (let i = 0; i < coordinates.length; i++) {
2026-10-07 17:58:17 +02:00
addPoint(route, coordinates[i][0], coordinates[i][1], coordinates[i][2]);
2025-12-23 16:49:47 +01:00
}
2026-10-07 17:58:17 +02:00
for (const key of graphhopperDetails) {
2026-10-09 08:58:00 +02:00
const detail = details[key] ?? [];
2025-12-23 16:49:47 +01:00
for (let i = 0; i < detail.length; i++) {
2026-10-07 17:58:17 +02:00
for (let j = detail[i][0]; j < detail[i][1] + (i == detail.length - 1 ? 1 : 0); j++) {
2025-12-23 16:49:47 +01:00
if (detail[i][2] !== undefined && detail[i][2] !== 'missing') {
if (key === 'road_class') {
2026-10-07 17:58:17 +02:00
route.highway[j] = detail[i][2];
2025-12-23 16:49:47 +01:00
} else if (key === 'hike_rating') {
2026-10-07 17:58:17 +02:00
route.sacScale[j] = hikeRatingToSACScale[detail[i][2]];
2025-12-23 16:49:47 +01:00
} else if (key === 'mtb_rating') {
2026-10-07 17:58:17 +02:00
route.mtbScale[j] = mtbRatingToScale[detail[i][2]];
2025-12-24 17:21:26 +01:00
} else if (key === 'surface' && detail[i][2] !== 'other') {
2026-10-07 17:58:17 +02:00
route.surface[j] = detail[i][2];
2025-12-23 16:49:47 +01:00
}
}
}
}
}
return route;
}
async function getBRouterRoute(
points: Coordinates[],
brouterProfile: string
2026-10-07 17:58:17 +02:00
): Promise<RoutedPoints> {
2026-10-08 18:34:19 +02:00
let url = `https://brouter.de/brouter?lonlats=${points.map((point) => `${point.lng.toFixed(8)},${point.lat.toFixed(8)}`).join('|')}&profile=${brouterProfile}&format=geojson&alternativeidx=0`;
2024-04-24 19:32:55 +02:00
let response = await fetch(url);
2024-04-27 11:16:59 +02:00
if (!response.ok) {
2026-10-09 08:58:00 +02:00
throw brouterError(await response.text());
2024-04-27 11:16:59 +02:00
}
2026-10-09 08:58:00 +02:00
return parseBRouterRoute(await response.json());
}
2024-04-24 19:32:55 +02:00
2026-10-09 08:58:00 +02:00
/** The error to throw for the error response of BRouter. Its message is a translation key. */
export function brouterError(error: string): Error {
if (error.includes('from-position not mapped in existing datafile')) {
return new Error('toolbar.routing.error.from');
} else if (error.includes('via1-position not mapped in existing datafile')) {
return new Error('toolbar.routing.error.via');
} else if (error.includes('to-position not mapped in existing datafile')) {
return new Error('toolbar.routing.error.to');
} else if (error.includes('Time-out')) {
return new Error('toolbar.routing.error.timeout');
}
return new Error(error);
}
/**
* The route of a response of BRouter (GeoJSON). The tags of the ways are in the `messages`, one
* per way: a way starts at the point whose position the message gives, and applies up to the
* next message.
*/
export function parseBRouterRoute(geojson: any): RoutedPoints {
2026-10-07 17:58:17 +02:00
const route = emptyRoute();
const coordinates = geojson.features[0].geometry.coordinates;
const messages = geojson.features[0].properties.messages;
2024-04-26 22:35:42 +02:00
2025-02-02 11:17:22 +01:00
const lngIdx = messages[0].indexOf('Longitude');
const latIdx = messages[0].indexOf('Latitude');
const tagIdx = messages[0].indexOf('WayTags');
2024-04-26 22:35:42 +02:00
let messageIdx = 1;
let tags = messageIdx < messages.length ? getTags(messages[messageIdx][tagIdx]) : {};
2024-04-26 22:35:42 +02:00
2024-04-24 19:32:55 +02:00
for (let i = 0; i < coordinates.length; i++) {
2026-10-07 17:58:17 +02:00
addPoint(route, coordinates[i][0], coordinates[i][1], coordinates[i][2]);
2024-04-26 22:35:42 +02:00
2025-02-02 11:17:22 +01:00
if (
messageIdx < messages.length &&
2024-04-26 22:35:42 +02:00
coordinates[i][0] == Number(messages[messageIdx][lngIdx]) / 1000000 &&
2025-02-02 11:17:22 +01:00
coordinates[i][1] == Number(messages[messageIdx][latIdx]) / 1000000
) {
2024-04-26 22:35:42 +02:00
messageIdx++;
if (messageIdx == messages.length) tags = {};
else tags = getTags(messages[messageIdx][tagIdx]);
2024-04-26 22:35:42 +02:00
}
2024-09-22 13:05:28 +02:00
2026-10-07 17:58:17 +02:00
route.surface[i] = tags.surface;
route.highway[i] = tags.highway;
route.sacScale[i] = tags.sac_scale;
route.mtbScale[i] = tags.mtb_scale;
2024-04-24 19:32:55 +02:00
}
return route;
2024-04-26 22:35:42 +02:00
}
2026-10-09 08:58:00 +02:00
/** The tags of a way, `key=value` separated by spaces, with the `:` of the keys as `_`. */
export function getTags(message: string): { [key: string]: string } {
2025-02-02 11:17:22 +01:00
const fields = message.split(' ');
let tags: { [key: string]: string } = {};
for (let i = 0; i < fields.length; i++) {
2025-02-02 11:17:22 +01:00
let [key, value] = fields[i].split('=');
2024-10-08 12:04:07 +02:00
key = key.replace(/:/g, '_');
tags[key] = value;
2024-04-26 22:35:42 +02:00
}
return tags;
}
2024-05-09 00:02:27 +02:00
2026-10-09 08:58:00 +02:00
/**
* The points of a straight route through `points`: one every 50 m, and the last one. The
* elevations are 0.
*/
export function interpolatePoints(points: Coordinates[]): RoutedPoints {
2026-10-07 17:58:17 +02:00
const route = emptyRoute();
const step = 0.05;
2024-05-09 00:02:27 +02:00
2025-02-02 11:17:22 +01:00
for (let i = 0; i < points.length - 1; i++) {
// Add intermediate points between each pair of points
2026-10-07 17:58:17 +02:00
const dist = distance(points[i], points[i + 1]) / 1000;
2024-05-09 00:02:27 +02:00
for (let d = 0; d < dist; d += step) {
2026-10-07 17:58:17 +02:00
const lat = points[i].lat + (d / dist) * (points[i + 1].lat - points[i].lat);
2026-10-08 18:34:19 +02:00
const lng = points[i].lng + (d / dist) * (points[i + 1].lng - points[i].lng);
addPoint(route, lng, lat, 0);
2024-05-09 00:02:27 +02:00
}
}
2026-10-07 17:58:17 +02:00
const last = points[points.length - 1];
2026-10-09 08:58:00 +02:00
if (last) {
addPoint(route, last.lng, last.lat, 0);
}
return route;
}
2024-05-09 00:02:27 +02:00
2026-10-09 08:58:00 +02:00
function getIntermediatePoints(points: Coordinates[]): Promise<RoutedPoints> {
const route = interpolatePoints(points);
2026-10-08 18:34:19 +02:00
return getElevation(route.lng.map((lng, i) => ({ lng, lat: route.lat[i] }))).then(
2026-10-07 17:58:17 +02:00
(elevations) => {
route.ele = elevations;
return route;
}
);
2025-02-02 11:17:22 +01:00
}