Recipes
Each recipe is a whole program that does what one of the TrailSplits tools does. The scripts need Node 18 or newer and nothing else. They run without a key on the daily allowance; set TRAILSPLITS_API_KEY to use your project's credits.
An elevation profile for a GPX file
Reads a GPX file, asks for its elevation profile, prints climb and descent, and writes distance, height and grade as CSV for any chart library.
// Elevation profile of a GPX file, as CSV.
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const gpx = readFileSync(process.argv[2], 'utf8');
const profile = await call('/v1/elevation-profile', { gpx, points: 500 });
const { ascent_m, descent_m, min_m, max_m, source } = profile.elevation;
console.error(`${(profile.input.length_m / 1000).toFixed(1)} km, +${ascent_m} m / -${descent_m} m, ${min_m}–${max_m} m (${source} heights)`);
// Rows under named columns; a file with gaps has several parts, and no line is drawn across a gap.
const col = Object.fromEntries(profile.series.columns.map((name, i) => [name, i]));
console.log('distance_km,elevation_m,grade_pct');
for (const row of profile.series.points) {
console.log([(row[col.distance_m] / 1000).toFixed(3), row[col.elevation_m], row[col.grade_pct]].join(','));
}
Get it: curl -O https://trailsplits.com/api/recipes/profile-csv.mjs
Run: node profile-csv.mjs my-hike.gpx > profile.csv
Clean and simplify a GPX file
Removes repeated and broken points, then keeps the shape within 10 m with fewer points. Names, waypoints and the climb stay. Writes the new file next to the old one.
// Clean a GPX file, then simplify it, keeping the shape within 10 m.
import { readFileSync, writeFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const path = process.argv[2];
const clean = await call('/v1/gpx/clean', { gpx: readFileSync(path, 'utf8') });
console.log(`clean: ${clean.report.points_before} → ${clean.report.points_after} points`);
const simple = await call('/v1/gpx/simplify', { gpx: clean.gpx, tolerance_m: 10 });
console.log(`simplify: kept ${simple.result.points}, removed ${simple.result.removed}, largest deviation ${simple.result.max_deviation_m} m`);
writeFileSync(path.replace(/\.gpx$/i, '') + '.tidy.gpx', simple.gpx);
Get it: curl -O https://trailsplits.com/api/recipes/tidy-gpx.mjs
Run: node tidy-gpx.mjs my-hike.gpx
A loop generator in 30 lines
Takes a start, a distance and a profile, asks for the best loop and three alternatives on signed trails, prints them as a table, and saves them as GeoJSON for any map.
// Hiking, running or cycling loops from a start point, saved as GeoJSON.
import { writeFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [lon, lat, km = '10', profile = 'hike'] = process.argv.slice(2);
const answer = await call('/v1/roundtrips', { start: [Number(lon), Number(lat)], distance_km: Number(km), profile, alternatives: 3 });
function decodePolyline6(s) { // lat,lon pairs at 1e-6 → [lon, lat]
const out = []; let i = 0, la = 0, lo = 0;
while (i < s.length) {
for (const axis of [0, 1]) {
let shift = 0, r = 0, b;
do { b = s.charCodeAt(i++) - 63; r |= (b & 31) << shift; shift += 5; } while (b >= 32);
const d = r & 1 ? ~(r >> 1) : r >> 1;
if (axis === 0) la += d; else lo += d;
}
out.push([lo / 1e6, la / 1e6]);
}
return out;
}
console.table(answer.loops.map((l) => ({ rank: l.rank, status: l.status, km: (l.distance_m / 1000).toFixed(1), up_m: l.ascent_m, minutes: l.time?.minutes ?? null, twice: `${Math.round(l.repeated_share * 100)}%` })));
const features = answer.loops.map((l) => ({ type: 'Feature', properties: { rank: l.rank, distance_m: l.distance_m, ascent_m: l.ascent_m }, geometry: { type: 'LineString', coordinates: decodePolyline6(l.shape) } }));
writeFileSync('loops.geojson', JSON.stringify({ type: 'FeatureCollection', features }));
Get it: curl -O https://trailsplits.com/api/recipes/loops.mjs
Run: node loops.mjs 7.7491 46.0207 12 hike
Race splits for a course
For a GPX course and a target time, prints a split for every kilometre, slower on the climbs and steep descents, with the terrain of each. Paste it on your wrist or into your watch.
// Splits every kilometre for a course and a target time.
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [path, target_time] = process.argv.slice(2);
const plan = await call('/v1/pace-plan', { gpx: readFileSync(path, 'utf8'), target_time });
const clock = (t) => { const s = Math.round(t); return `${Math.floor(s / 3600)}:${String(Math.floor(s / 60) % 60).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`; };
const pace = (t) => { const s = Math.round(t); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}/km`; };
console.log(`${(plan.course.distance_m / 1000).toFixed(1)} km, +${plan.course.gain_m} m, in ${clock(plan.target.seconds)} (${plan.course.heights} heights)`);
for (const s of plan.splits) console.log(`${s.label.padStart(8)} ${pace(s.pace_s_per_km).padStart(9)} ${clock(s.cumulative_seconds)} ${s.character}`);
for (const u of plan.unknowns) console.log('note:', u.message);
Get it: curl -O https://trailsplits.com/api/recipes/splits.mjs
Run: node splits.mjs my-race.gpx 2:30:00
The best day for this hike
For a GPX file, the next seven days × start times ordered by no thunderstorm signal, dry, then daylight, with the facts that placed the top three. An ordering of facts, never a safety score. Instead of a file you can send geometry (a GeoJSON line), such as a round trip’s decoded shape; add calm to prefer to separate windows that tie.
// Which day and start time this week, by your own preferences.
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const answer = await call('/v1/route-windows', { gpx: readFileSync(process.argv[2], 'utf8'), days: 7, prefer: ['no_thunder', 'dry', 'daylight'] });
if (!answer.best) { console.log('No window could be read:', answer.unknowns.map((u) => u.message).join(' ')); process.exit(0); }
console.log(`Best: ${answer.best.date_local} at ${answer.best.start_local} (${answer.settings.timezone})`);
for (const w of answer.windows.slice(0, 3)) {
console.log(`\n#${w.rank} ${w.date_local} ${w.start_local}, back by ${w.finish_local.slice(11, 16)}${w.complete ? '' : ' (some hours missing)'}`);
for (const reason of w.why) console.log(' - ' + reason);
}
console.log('\n' + answer.note);
Get it: curl -O https://trailsplits.com/api/recipes/best-day.mjs
Run: node best-day.mjs my-hike.gpx
Where can I leave this trail
For a GPX file, the longest stretch with no public road, stop or village within an hour’s walk, then every kilometre the nearest way out of each kind with its walking minutes and name. A mapped way out, never a safe one: a road can be closed, lifts and pass buses can be seasonal, and a hut is shelter, not a way out.
// The ways out along a hike, every kilometre.
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const answer = await call('/v1/route-exits', { gpx: readFileSync(process.argv[2], 'utf8') });
const name = new Map(answer.exits.map((e) => [e.id, e.name]));
const km = (m) => (m / 1000).toFixed(1);
const s = answer.longest_without_exit.stretch;
console.log(s ? `Longest stretch with no road, stop or village within ${answer.longest_without_exit.within_minutes} min: ${km(s.length_m)} km (km ${km(s.from_m)} to ${km(s.to_m)})` : 'A road, stop or village within the hour all along.');
for (const a of answer.along) {
const near = ['road', 'transport', 'settlement', 'hut'].map((kind) => {
const x = a[kind];
return x ? `${kind} ${x.minutes} min${name.get(x.exit) ? ` (${name.get(x.exit)})` : ''}` : `no ${kind}`;
});
console.log(`km ${km(a.at_m).padStart(5)} ${near.join(' · ')}`);
}
for (const u of answer.unknowns) console.log('note:', u.message);
console.log(answer.note);
Get it: curl -O https://trailsplits.com/api/recipes/exits.mjs
Run: node exits.mjs my-hike.gpx
Weather along a hike
For a GPX file and a departure time, prints the forecast at each point at the hour you reach it, at that point's own height. Missing hours stay missing.
// The weather at each part of a hike, at the hour you get there.
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [path, departure] = process.argv.slice(2); // departure with its offset, up to 16 days ahead
const answer = await call('/v1/route-weather', { gpx: readFileSync(path, 'utf8'), departure, profile: 'hike' });
for (const s of answer.samples) {
const where = `${(s.at_m / 1000).toFixed(1).padStart(5)} km ${s.kind.padEnd(5)} ${String(s.arrival_local).slice(11, 16)}`;
const w = s.weather;
console.log(w ? `${where} ${w.temp_c} °C, rain ${w.precip_probability_pct ?? '?'}%, wind ${w.wind_kmh ?? '?'} km/h` : `${where} no forecast (${s.missing})`);
}
console.log(answer.forecast.provider.attribution); // show this next to the values
Get it: curl -O https://trailsplits.com/api/recipes/hike-weather.mjs
Run: node hike-weather.mjs my-hike.gpx 2026-10-10T07:30:00+02:00
A map with 3D terrain
One HTML file: the TrailSplits outdoor map with hillshading and 3D terrain from the TrailSplits elevation tiles. Drag with the right mouse button (or two fingers) to tilt.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>3D terrain with TrailSplits</title>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@6.15.0/dist/maplibre-gl.css">
<script src="https://unpkg.com/pmtiles@4.5.0/dist/pmtiles.js"></script>
<style>body { margin: 0; } #map { height: 100vh; }</style>
</head>
<body>
<div id="map"></div>
<script type="module">
import * as maplibregl from 'https://unpkg.com/maplibre-gl@6.15.0/dist/maplibre-gl.mjs';
// A same-origin module worker can import the CDN worker; browsers reject a cross-origin Worker URL.
maplibregl.setWorkerUrl(URL.createObjectURL(new Blob([
'import "https://unpkg.com/maplibre-gl@6.15.0/dist/maplibre-gl-worker.mjs";',
], { type: 'text/javascript' })));
const API = 'https://api.trailsplits.com';
maplibregl.addProtocol('pmtiles', new pmtiles.Protocol().tile);
const map = new maplibregl.Map({
container: 'map', style: API + '/styles/current/trailsplits_openmaptiles_style.json',
center: [7.6586, 45.9764], zoom: 12.5, pitch: 65, bearing: -20, maxPitch: 80,
attributionControl: { customAttribution: '© TrailSplits' },
});
map.on('load', () => {
// Map tiles, terrain and styles need no key and are not counted.
map.addSource('dem', { type: 'raster-dem', tiles: [API + '/tiles/v1/terrainrgb/current/{z}/{x}/{y}.png'], tileSize: 256, encoding: 'mapbox', maxzoom: 12,
attribution: "Terrain and contours in Switzerland © swisstopo (swissALTI3D). Terrain and contours produced using Copernicus WorldDEM-30 © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved" });
map.setTerrain({ source: 'dem', exaggeration: 1.3 });
map.addLayer({ id: 'hillshade', type: 'hillshade', source: 'dem', paint: { 'hillshade-exaggeration': 0.35 } }, map.getStyle().layers.find((l) => l.type === 'symbol')?.id);
});
</script>
</body>
</html>
Get it: curl -O https://trailsplits.com/api/recipes/terrain.html
Run: Open terrain.html in a browser.
Time a route for one person
Fits a person’s own pace from their recent timed walks, then asks route analysis for a planned route with that pace: the model’s moving time and theirs, with an 80 % range. The walks are not stored anywhere.
// A planned route timed for one person, from their own recorded walks (GPX with <time> on the track points).
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [route, ...walks] = process.argv.slice(2);
if (!route || !walks.length) throw new Error('usage: node personal-time.mjs planned-route.gpx walk-1.gpx [walk-2.gpx …]');
// 1. The person's pace against the TrailSplits hike time model. Nothing is kept; the answer has no coordinates or times.
const fit = await call('/v1/time-model/fit', { activities: walks.map((file) => ({ gpx: readFileSync(file, 'utf8') })) });
const p = fit.pace_profile;
console.error(`Fitted on ${p.activities} walk(s): level ×${p.factors.level}, up ×${p.factors.up}, down ×${p.factors.down}`);
for (const u of fit.unknowns) console.error(` ${u.message}`);
// 2. The planned route with that pace. Send pace_profile exactly as it came back: it names the model version it fits.
const analysis = await call('/v1/route-analysis', { gpx: readFileSync(route, 'utf8'), profile: 'hike', pace_profile: p });
const t = analysis.time;
const hm = (min) => `${Math.floor(min / 60)} h ${String(Math.round(min % 60)).padStart(2, '0')} min`;
console.log(`${(analysis.input.length_m / 1000).toFixed(1)} km`);
console.log(`The model: ${hm(t.minutes)} moving, without breaks`);
if (t.personal) console.log(`You: ${hm(t.personal.minutes)} (80 % of days between ${hm(t.personal.interval_80[0])} and ${hm(t.personal.interval_80[1])})`);
// time.personal.profile holds [metres, minutes] along the line, for a chart or a timetable of waypoints.
Get it: curl -O https://trailsplits.com/api/recipes/personal-time.mjs
Run: node personal-time.mjs planned-route.gpx walk-1.gpx walk-2.gpx walk-3.gpx
Day outings near a place
Asks for day outings near a point (at most four hours, T2, starting at a stop), with tomorrow’s go window, and prints each with its facts and why it is listed. Made for agents and chat answers; facts, not a rating.
// Day outings near a point, with tomorrow's go window.
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [lat, lon] = process.argv.slice(2).map(Number);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) throw new Error('usage: node outings.mjs <lat> <lon>');
const tomorrow = new Date(Date.now() + 86_400_000).toISOString().slice(0, 10);
const answer = await call('/v1/outings', { lat, lon, radius_km: 20, date: tomorrow, max_hours: 4, max_grade: 'T2', car_free: true });
for (const o of answer.outings) {
const climb = o.ascent_m === null ? 'climb unknown' : `+${o.ascent_m} m`;
console.log(`${o.rank}. ${o.name ?? 'A round trip from your point'} (${(o.length_m / 1000).toFixed(1)} km, ${climb}, ${o.moving_minutes ?? '?'} min)`);
if (o.url) console.log(` ${o.url}`);
for (const why of o.why) console.log(` - ${why}`);
}
// What each rule left out (it never passes an outing it cannot judge), and what the list does not assess.
console.log('left out:', answer.left_out);
for (const u of answer.unknowns) console.log(`note: ${u.message}`);
Get it: curl -O https://trailsplits.com/api/recipes/outings.mjs
Run: node outings.mjs 46.6863 7.8632
A place, the signed trails and the huts near it
Finds a place by name, lists signed hiking routes by the same name, and the huts and shelters within a few kilometres of the place, each with its height.
// A place by name, signed trails by name, and huts near the place.
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
async function get(path) {
const res = await fetch(API + path, { headers });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [placeName, trailName = placeName] = process.argv.slice(2);
if (!placeName) throw new Error('usage: node places-and-trails.mjs <place> [trail name]');
// Search answers places and signed trails by name: take the first answer that is a place, not a trail.
const places = await get('/search/v1/forward?' + new URLSearchParams({ q: placeName, limit: '5' }));
const place = places.features.find((f) => f.kind !== 'trail');
if (!place) throw new Error(`no place called ${placeName}`);
const [lon, lat] = place.center;
console.log(`${place.name} (${place.kind}) at ${lat.toFixed(4)}, ${lon.toFixed(4)}`);
const trails = await get('/trails/v1/search?' + new URLSearchParams({ q: trailName, limit: '5' }));
for (const t of trails.features) console.log(` trail: ${t.properties.name}${t.properties.ref ? ` (${t.properties.ref})` : ''}, ${(t.properties.distance_m / 1000).toFixed(0)} km, ${t.properties.network ?? 'network unknown'}`);
// A box of about 5 km around the place (each side at most 2 degrees).
const d = 0.045;
const huts = await get(`/pois/v1/bbox?min_lat=${lat - d}&min_lon=${lon - d}&max_lat=${lat + d}&max_lon=${lon + d}&kind=hut&limit=10`);
for (const h of huts.features) console.log(` hut: ${h.name ?? 'unnamed'}${h.ele !== null ? `, ${Math.round(h.ele)} m` : ''}`);
// Show "© OpenStreetMap contributors" wherever you show these results.
Get it: curl -O https://trailsplits.com/api/recipes/places-and-trails.mjs
Run: node places-and-trails.mjs "Zermatt" "Haute Route"
Heights and snow along a line
Samples the terrain height at points of a line (from the published terrain release) and asks how much of it is under snow by satellite, with the 24 h and 48 h outlook kept apart.
// Terrain heights and snow cover at points of a line ("lon,lat|lon,lat|...").
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
async function get(path) {
const res = await fetch(API + path, { headers });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const points = (process.argv[2] ?? '7.7491,46.0207|7.7300,46.0100|7.7100,46.0000').split('|').map((p) => p.split(',').map(Number));
const latLon = points.map(([lon, lat]) => `${lat},${lon}`).join('|');
// Heights come from the published terrain release; the manifest names it (no key, not counted).
const manifest = await get('/pmtiles/current/manifest.json');
const release = manifest.artifacts.terrain.version;
const heights = await get(`/tiles/v1/elevation/${release}/sample?points=${encodeURIComponent(latLon)}&z=12&encoding=mapbox`);
heights.points.forEach((p, i) => console.log(`point ${i + 1}: ${p.elevation_m === null ? 'no height' : Math.round(p.elevation_m) + ' m'}`));
// Snow by satellite at the same points; outlook kept apart from observation.
const snow = await get(`/tiles/v1/snow/route-forecast?points=${encodeURIComponent(latLon)}&evidence=1&revision=recipe1`);
const s = snow.evidence.summary;
console.log(`snow ${s.percent_snow} %, clear ${s.percent_clear} %, unknown ${s.percent_unknown} % (coverage ${s.coverage})`);
console.log('Snow seen from space is evidence, not a safety assessment.');
Get it: curl -O https://trailsplits.com/api/recipes/heights-and-snow.mjs
Run: node heights-and-snow.mjs "7.7491,46.0207|7.7300,46.0100|7.7100,46.0000"
Surfaces of a recorded line, and a map image of it
Matches a recorded line to the mapped paths and sums its length by surface and by SAC grade, then renders a small PNG map of the line with its attribution drawn in.
// Surfaces and grades of a GPX track, and a PNG map of it.
import { readFileSync, writeFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const gpx = readFileSync(process.argv[2], 'utf8');
const coords = [...gpx.matchAll(/<trkpt[^>]*lat="([-\d.]+)"[^>]*lon="([-\d.]+)"/g)].map((m) => [Number(m[2]), Number(m[1])]);
if (coords.length < 2) throw new Error('no track points');
const shape = coords.filter((_, i) => i % Math.ceil(coords.length / 2000) === 0).map(([lon, lat]) => ({ lat, lon }));
const matched = await call('/valhalla/trace_attributes', { shape, costing: 'pedestrian', shape_match: 'map_snap' });
const bySurface = {};
for (const e of matched.edges) {
const key = `${e.surface ?? 'unknown'}${e.trailsplits_surface_tagged === false ? ' (class default)' : ''}`;
bySurface[key] = (bySurface[key] ?? 0) + e.length; // kilometres
}
for (const [surface, km] of Object.entries(bySurface).sort((a, b) => b[1] - a[1])) console.log(`${surface}: ${km.toFixed(2)} km`);
// A 640 x 400 map of the line; the attribution is drawn into the image: keep it visible.
const lons = coords.map((c) => c[0]), lats = coords.map((c) => c[1]);
const res = await fetch(API + '/static-map/render', { method: 'POST', headers, body: JSON.stringify({ bbox: [Math.min(...lons), Math.min(...lats), Math.max(...lons), Math.max(...lats)], width: 640, height: 400, padding: 24, geojson: { type: 'LineString', coordinates: coords } }) });
if (!res.ok) throw new Error(`static map: ${res.status}`);
writeFileSync('line.png', Buffer.from(await res.arrayBuffer()));
console.log('wrote line.png');
Get it: curl -O https://trailsplits.com/api/recipes/match-and-map.mjs
Run: node match-and-map.mjs my-walk.gpx
Keep your Valhalla code: a route on signed trails
Sends a Valhalla-style request to POST /route/v1 and decodes the answer’s polyline: code written for Valhalla or OSRM-style answers gets TrailSplits’ hiking router with almost no change.
// A walking route between two points, in the Valhalla-compatible shape.
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [a, b] = process.argv.slice(2).map((p) => p.split(',').map(Number));
if (!a || !b) throw new Error('usage: node valhalla-route.mjs <lat,lon> <lat,lon>');
const answer = await call('/route/v1', { locations: [{ lat: a[0], lon: a[1] }, { lat: b[0], lon: b[1] }], costing: 'pedestrian' });
// Polyline with 6 decimals, decoded to [lon, lat].
function decode(str) {
let i = 0, lat = 0, lon = 0; const out = [];
while (i < str.length) {
for (const k of [0, 1]) {
let shift = 0, result = 0, byte;
do { byte = str.charCodeAt(i++) - 63; result |= (byte & 0x1f) << shift; shift += 5; } while (byte >= 0x20);
const d = result & 1 ? ~(result >> 1) : result >> 1;
if (k === 0) lat += d; else lon += d;
}
out.push([lon / 1e6, lat / 1e6]);
}
return out;
}
const route = answer.routes[0];
console.log(`${(route.distance / 1000).toFixed(2)} km, ${Math.round(route.duration / 60)} min, ${decode(route.geometry).length} points`);
Get it: curl -O https://trailsplits.com/api/recipes/valhalla-route.mjs
Run: node valhalla-route.mjs 46.0207,7.7491 46.0036,7.7355
Brief a day’s route: water, huts, steep ground
One brief for a day’s line (analysis and places), the places along it in order, and the stretches where the terrain at the path is 30° or steeper (experimental), each read from its own operation.
// A day's route briefed: notices, places in order, and steep stretches.
import { readFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const gpx = readFileSync(process.argv[2], 'utf8');
const brief = await call('/v1/route-brief', { gpx, include: ['analysis', 'places'] });
console.log(`${(brief.line.length_m / 1000).toFixed(1)} km`);
for (const n of brief.notices) console.log(`notice: ${n.message}`);
const places = await call('/v1/route-places', { gpx, within_m: 300, kinds: ['water', 'spring', 'hut', 'shelter'] });
for (const p of places.places) console.log(` ${(p.at_m / 1000).toFixed(1)} km: ${p.kind}${p.name ? ` ${p.name}` : ''} (${p.offset_m} m off the line)`);
const slopes = await call('/v1/route-slopes', { gpx });
console.log(`slope at the path (experimental): ${slopes.totals.from_30_m} m at 30° or more, ${slopes.totals.from_40_m} m at 40° or more`);
console.log('Mapped is not a promise: water may not run, huts may be closed, and a slope is not an avalanche assessment.');
Get it: curl -O https://trailsplits.com/api/recipes/day-brief.mjs
Run: node day-brief.mjs my-day.gpx
A route card as a PDF
Turns a GPX file into a printable route card (map, profile, legs, water and huts) as a PDF on A4. Nothing is stored or published.
// A printable route card (PDF, A4) for a GPX file.
import { readFileSync, writeFileSync } from 'node:fs';
const API = 'https://api.trailsplits.com';
const headers = { 'Content-Type': 'application/json', ...(process.env.TRAILSPLITS_API_KEY ? { Authorization: `Bearer ${process.env.TRAILSPLITS_API_KEY}` } : {}) };
async function call(path, body) {
const res = await fetch(API + path, { method: 'POST', headers, body: JSON.stringify(body) });
const answer = await res.json();
if (!res.ok) throw new Error(`${res.status} ${answer.error?.code ?? answer.error ?? ''}: ${answer.error?.message ?? answer.message ?? ''}`);
return answer;
}
const [file, name = 'My route'] = process.argv.slice(2);
const res = await fetch(API + '/v1/route-card', { method: 'POST', headers, body: JSON.stringify({ gpx: readFileSync(file, 'utf8'), name, format: 'pdf', paper: 'a4' }) });
if (!res.ok) throw new Error(`${res.status}: ${(await res.json()).error?.message ?? ''}`);
writeFileSync('route-card.pdf', Buffer.from(await res.arrayBuffer()));
console.log('wrote route-card.pdf');
Get it: curl -O https://trailsplits.com/api/recipes/route-card.mjs
Run: node route-card.mjs my-hike.gpx "My hike"