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

300 lines
9.8 KiB
TypeScript
Raw Normal View History

2026-10-07 17:58:17 +02:00
import { distance, type Coordinates } from 'gpx';
2025-10-17 23:54:45 +02:00
import { settings } from '$lib/logic/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)[];
};
function emptyRoute(): RoutedPoints {
return { lng: [], lat: [], ele: [], surface: [], highway: [], sacScale: [], mtbScale: [] };
}
/** Adds a trackpoint, which has the elevation of the previous one if it has none. */
function addPoint(route: RoutedPoints, lng: number, lat: number, ele: number | undefined) {
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
const graphhopperBlockPrivateCustomModels: { [key: string]: any } = {
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',
},
],
},
motorcycle: {
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({
points: points.map((point) => [point.lon, point.lat]),
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-03-07 15:57:58 +01:00
const error = await response.json();
if (error.message.includes('Cannot find point 0')) {
throw new Error('toolbar.routing.error.from');
} else if (error.message.includes('Cannot find point 1')) {
if (points.length == 3) {
throw new Error('toolbar.routing.error.via');
} else {
throw new Error('toolbar.routing.error.to');
}
} else if (error.hints[0].details.includes('PointDistanceExceededException')) {
throw new Error('toolbar.routing.error.distance');
} else if (error.hints[0].details.includes('ConnectionNotFoundException')) {
throw new Error('toolbar.routing.error.connection');
} else {
throw new Error(error.message);
}
2025-12-23 16:49:47 +01:00
}
let json = await response.json();
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) {
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> {
2025-12-23 16:49:47 +01:00
let url = `https://brouter.de/brouter?lonlats=${points.map((point) => `${point.lon.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-03-07 15:57:58 +01:00
const error = await response.text();
if (error.includes('from-position not mapped in existing datafile')) {
throw new Error('toolbar.routing.error.from');
} else if (error.includes('via1-position not mapped in existing datafile')) {
throw new Error('toolbar.routing.error.via');
} else if (error.includes('to-position not mapped in existing datafile')) {
throw new Error('toolbar.routing.error.to');
} else if (error.includes('Time-out')) {
throw new Error('toolbar.routing.error.timeout');
} else {
throw new Error(error);
}
2024-04-27 11:16:59 +02:00
}
2024-04-24 19:32:55 +02:00
let geojson = await response.json();
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
}
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-07 17:58:17 +02:00
function getIntermediatePoints(points: Coordinates[]): Promise<RoutedPoints> {
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);
const lon = points[i].lon + (d / dist) * (points[i + 1].lon - points[i].lon);
addPoint(route, lon, lat, 0);
2024-05-09 00:02:27 +02:00
}
}
2026-10-07 17:58:17 +02:00
const last = points[points.length - 1];
addPoint(route, last.lon, last.lat, 0);
2024-05-09 00:02:27 +02:00
2026-10-07 17:58:17 +02:00
return getElevation(route.lng.map((lng, i) => ({ lon: lng, lat: route.lat[i] }))).then(
(elevations) => {
route.ele = elevations;
return route;
}
);
2025-02-02 11:17:22 +01:00
}