English · Česky
A smooth 3D fly-over of a GPS track: real-time preview in the browser and MP4/WebM video export for social media. A framework-independent component built on MapLibre GL.
▶ Try the live demo with the sample ride or your own GPX file.
The first seconds of a video exported by the demo (whole video, 24 s, MP4).
- Smooth by construction. The camera is a pure function of time, computed up front from a resampled and smoothed track. No keyframes, no per-frame waiting for the map.
- The video is the preview. Export renders the same flight frame by frame and waits for every map tile, so nothing is blurry or missing, however fast the flight.
- Three modes: 3D fly-over, a 2D map that follows the track, and a static view of the whole route where only the line runs.
- Place names only for places the track really passes, appearing as the trail approaches them.
- No API keys. Satellite, topographic and black-and-white basemaps work out of the box; an optional winter filter turns any of them snowy.
- Stops for photos, an elevation profile, coloured markers for apps that tell a richer story.
- English by default, Czech built in (
locale: 'cs'), any text can be overridden.
- A browser with WebGL 2, and WebCodecs for video export: Chrome, Edge, Firefox 130+, Safari 16.4+.
- Node.js 22.18 or newer: tests and scripts run straight from TypeScript, with no build step.
- Python 3, only for the demo server (
npm run serve). - No API keys or environment variables: every built-in basemap is keyless.
git clone https://github.com/zpracny/trail-flyover.git && cd trail-flyover
npm ci
npm run build && npm run serve # demo at http://127.0.0.1:8811
npm run check # types, linter (Biome) and tests
npm run build:lib # the package apps install: dist/ (JavaScript + type declarations)
npm run compare # smoothness compared with a keyframe camera
Tests: 112 tests in about 10 s, on a real 121 km recording, a 46 km section of it, and synthetic and random tracks. GitHub Actions runs the same checks on every push.
The package is not on npm yet. Install a released version from GitHub; the app provides
maplibre-gl (5 or newer):
npm install https://github.com/zpracny/trail-flyover/releases/download/v0.5.7/trail-flyover-0.5.7.tgz maplibre-gl
That is a ready-built package (ES modules with type declarations in dist/), pinned by a
checksum in your lockfile. Installing straight from git also works
(npm install github:zpracny/trail-flyover#v0.5.7); npm then builds the package on install.
Prefer the tarball on build servers: npm records a git install as git+ssh://, which needs an
SSH key there.
Verified in November 2026 with trail-flyover 0.5.2 and MapLibre 6.20, each time on a fresh app: production build, the page in Chrome, the map loaded, a video exported.
| build | dev server | |
|---|---|---|
Next.js 16.4, Turbopack (next build) |
✅ | ✅ next dev |
Next.js 16.4, webpack (next build --webpack) |
✅ | — |
Vite 8.4 (vite build) |
✅ | ✅ vite |
Also: type-checking with TypeScript 5.7 (moduleResolution: "bundler", strict or not), esbuild,
importing the core in Node. The author's app TrailMetrics runs it in a Next.js 16 app (webpack
build) on Vercel. No transpilePackages or other bundler settings are
needed: the package ships compiled JavaScript.
One step every MapLibre 6 app needs. MapLibre 6 is ES modules only and loads its worker from the file next to its own, which a bundler moves and renames. Without the step below the map fails with "Worker failed to load". Tell MapLibre where the worker went, once, before the first map:
import * as maplibregl from 'maplibre-gl';
maplibregl.setWorkerUrl(new URL('maplibre-gl/dist/maplibre-gl-worker.mjs', import.meta.url).toString());Next.js (Turbopack and webpack) and Vite then ship the worker as a file of the app itself, so a
Content Security Policy needs no blob: for it (see below). MapLibre 5 does not need this step.
import * as maplibregl from 'maplibre-gl'; // MapLibre 6 has no default export
import { TrailFlyover, parseGpx } from 'trail-flyover';
const fly = new TrailFlyover(element, {
maplibregl, // the app's own instance (no second copy)
output: { width: 1080, height: 1920 }, // Story; Feed 1080×1350, Wide 1920×1080
basemap: 'esri-satellite', // or 'cuzk-ortofoto', 'esri-light', your own BasemapDef…
flight: { preset: 'drone', duration: 30 }, // drone | low | overview; camera: 'static' = whole route
labels: [{ lon: 13.733, lat: 46.183, name: 'Tolmin', kind: 'town' }], // only those on the route are shown
});
await fly.load(parseGpx(gpxText).points, { title: 'Tolmin – Koper', subtitle: '13 June 2026' });
fly.play(); // real-time preview
await fly.prefetch(p => console.log(p)); // optional: load tiles first, then playback has no holes
const video = await fly.exportVideo({ format: 'mp4', fps: 30, onProgress });
console.log(video.stats); // where the time went: { tiles, render, overlay, encode, … } in ms
const photo = await fly.exportImage();
fly.on('time', t => …); fly.on('state', s => …);
fly.destroy();exportVideo({ format, fps, bitrate, onProgress, signal }) renders the flight frame by frame and
returns { blob, mimeType, extension, codec, stats }.
format:'mp4'(H.264, otherwise HEVC, AV1 or VP9) or'webm'(VP9, AV1, VP8).bitratein bits per second. The default is 0.2 bit per pixel per frame, between 6 and 24 Mbit/s: 12.4 Mbit/s for 1080×1920 at 30 fps, 8.7 Mbit/s for 1080×1350. A fast flight over aerial imagery changes the whole picture in every frame, so a lower bitrate shows quickly as blocky edges, also around the place names.signalcancels the export (AbortError), as doesdestroy().statssays where the time went:tileslarge means a slow network,encodelarge a slow encoder (no hardware encoding).
The player expects to be called in quick succession (sliders, React effects):
load()andupdate()are queued. With severalload()calls in a row only the last track is built; the earlier calls finish without doing any work.update()may be called whileload()is still running. An invalid change (unknown basemap, missing key) fails and changes nothing.- During an export or a prefetch,
load(),update()and another export fail with an error ("An export or prefetch is in progress…").seek()andplay()are ignored in that time. - While an export or a prefetch runs, the player shows the picture from the moment it started,
still: the map underneath jumps from frame to frame waiting for tiles, which would look jerky.
stillWhileBusy: falseshows the work live. - A page that does not render (background tab, covered or minimised window) gets no animation
frames, and MapLibre cannot load without them.
load()then waits instead of failing: its 20 s limit counts only time in which the page renders. prefetch()is meant for smooth playback. An export does not need it: it waits for every tile of every frame anyway.destroy()may be called at any time, even in the middle of loading or exporting. A load in progress is dropped and no extra map is left behind; an export ends withAbortError.- An unreachable or missing tile does not make
load()fail. The map is completed when the tile arrives.
An app with its own look passes its own function instead of the default panel. The player keeps drawing the place labels and the tip of the trail:
new TrailFlyover(el, {
maplibregl,
hud: (ctx, f) => {
// f.width, f.height, f.scale (min(w,h)/1080), f.stats.distance / ascent / moving / elapsed,
// f.total, f.progress, f.project(lon, lat) → a point in output pixels
drawMyStats(ctx, f);
},
});Give the flight places to stop at. The trail and the camera slow down smoothly, stand still for
the given time and set off again; the app draws whatever belongs there (a photo card, a note)
in its hud function.
const fly = new TrailFlyover(el, {
maplibregl,
flight: {
duration: 30, // the flight itself; stops come on top
stops: [
{ time: photo.takenAt, duration: 3, data: photo }, // by timestamp of the recording…
{ lon: 13.65, lat: 45.96, duration: 5, data: gallery }, // …by place (first pass within 500 m)…
{ distance: 60_000, duration: 2 }, // …or by metres along the track
],
},
hud: (ctx, f) => {
drawMyStats(ctx, f);
if (f.stop) {
// f.stop.stop.data is what you passed in; elapsed / remaining / progress say where in the stop we are
const alpha = Math.min(1, f.stop.elapsed / 0.5, f.stop.remaining / 0.5); // fade in and out
drawPhotoCard(ctx, f.stop.stop.data, alpha);
}
},
});- The video is
durationplus the sum of the stops (fly.durationis the total). - Stops that cannot be placed (a timestamp outside the recording, a place further than
stopMaxOffTrackfrom the track, no duration) are left out;fly.flightPlan.stopslists the ones in use, in the order the trail reaches them, with theirstartandendtimes. - The camera settles for a moment after the trail stops and is at rest in the middle of a stop.
- Stops work with every camera, including the static whole-route view.
elevationProfile: true adds a profile to the built-in panel. With your own hud, draw it where
you like:
import { drawElevationProfile } from 'trail-flyover';
hud: (ctx, f) => {
drawElevationProfile(ctx, f, { x: 60, y: f.height - 320, width: f.width - 120, height: 120 });
// f.profile holds the data (distance and elevation arrays, min, max) if you want your own drawing
}Whole-route shots (the overviews and the static camera) keep the track clear of the panels. If yours are bigger than the built-in ones, or you want to respect the safe zones of a social network, say how much of the picture to keep free:
flight: { margins: { top: 0.2, bottom: 0.3, side: 0.07 } } // fractions of the height / widthA panel on one side only (a stats column on the right of a wide video): left / right override
side for that edge. The overviews, the follow camera and the place names then use the free part:
flight: { margins: { top: 0.14, bottom: 0.08, left: 0.04, right: 0.34 } }During the follow flight the trail tip sits at about 60–65 % of the picture height. Above a tall
bottom panel that is right at its edge, and a place the trail has just passed disappears under the
panel at once. tipPosition puts the tip into the free band between the margins instead
(0 = its top, 0.5 = its middle, 1 = its bottom):
flight: { margins: { top: 0.16, bottom: 0.4 }, tipPosition: 0.5 }The built-in panel and the status messages are English; locale: 'cs' switches them to Czech and
strings: { distance: 'Strecke', … } replaces single texts. Errors thrown to the developer are
always in English.
The component works with the DOM and WebGL, so in Next.js it belongs in a client component:
'use client';
import { useEffect, useRef } from 'react';
import * as maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import { TrailFlyover, type TrackPoint } from 'trail-flyover';
// MapLibre 6: where the bundler put the worker (see "Bundlers and frameworks").
if (typeof window !== 'undefined') {
maplibregl.setWorkerUrl(new URL('maplibre-gl/dist/maplibre-gl-worker.mjs', import.meta.url).toString());
}
export function Flyover({ points, title }: { points: TrackPoint[]; title: string }) {
const ref = useRef<HTMLDivElement>(null);
const fly = useRef<TrailFlyover | null>(null);
useEffect(() => {
if (!ref.current) return;
const f = new TrailFlyover(ref.current, { maplibregl });
fly.current = f;
f.load(points, { title }).catch(err => console.error(err));
return () => {
f.destroy();
fly.current = null;
};
}, [points, title]);
return <div ref={ref} style={{ width: '100%', aspectRatio: '4 / 5' }} />;
}- This exact component, used from a server page, builds and runs in Next.js 16 as it is: the page is prerendered on the server and the map starts in the browser.
destroy()is safe in the middle ofload(), so React running the effect twice in development mode is not a problem.- MapLibre and the player add about 400 kB (gzip) of JavaScript. To keep them out of the first
load of a page, load the component only when it is needed:
const Flyover = dynamic(() => import('./Flyover').then(m => m.Flyover), { ssr: false }).
This policy was tested with a Next.js 16 build (satellite basemap, terrain, video export) and blocked nothing:
default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';
worker-src 'self'; img-src 'self' data: blob:;
connect-src 'self' https://server.arcgisonline.com https://s3.amazonaws.com https://tiles.openfreemap.org
-
worker-src 'self'is enough once the worker URL is set as above. -
connect-srclists the servers the map talks to. Tiles are downloaded withfetch, so they belong there, not only inimg-src. Add the hosts of the basemaps you offer:for host esri-satellite,esri-satellite-bw,esri-topo,esri-light,esri-dark; alsocuzk-ortofoto(Esri beyond the border)https://server.arcgisonline.comesri-wayback-2022https://wayback.maptiles.arcgis.comcuzk-ortofotohttps://ags.cuzk.gov.czopentopomaphttps://a.tile.opentopomap.org(alsob.,c.)terrain (always) https://s3.amazonaws.comfetchPlaceLabelshttps://tiles.openfreemap.org(withsource: 'overpass': the Overpass servers) -
script-src 'unsafe-inline'is there for Next.js itself, not for the library.
They differ in just two options.
| Mode | What it does | Options |
|---|---|---|
| Whole route | the map stands still, the whole route is in view and only the line runs | mode: '2d', flight: { camera: 'static' } |
| Map flight | a 2D map glides along with the track, north up | mode: '2d' |
| 3D fly-over | terrain, a tilted camera flies along the track | default |
| Whole route in 3D | a tilted view of the whole route with terrain, only the line runs | flight: { camera: 'static' } |
The map flight (mode: '2d') looks straight at the tip of the trail, so on a short twisty loop
the map follows the line closely instead of the line wandering to the edge. With tipPosition the
tip sits in the free band between your panels.
The static camera (camera: 'static'):
- The shot is computed exactly so that the whole route fits between the title and the stats panel.
- In 2D north is up. In 3D, or with
northUp: false, the view turns when that makes the route considerably larger (an east–west route in the Story format). - The video is shorter: 8 s + 0.15 s/km, at most 24 s.
introis how long the empty map is shown,outrohow long the finished line stays. - Any length from 3 s can be set (
flight.duration), for every camera. - Small places disappear again after 3.5 s; towns stay as landmarks.
Not every label passed in (labels) is shown. Only places the track really passes remain, and
each one appears as the tip of the trail approaches it.
- Time to read (
labelLead, default 1.2 s): a name appears this long before the trail gets there. A following camera leaves a passed place behind within a fraction of a second (it drops out of the bottom of the picture), so a name is read while the place is still ahead. Measured on the Tolmin–Koper track, 20 s video with a tall bottom panel: every name readable for at least 1.2 s (median 1.6 s), before only 0.4 s (median).0= appear exactly as the trail arrives. - Size (
labelSize, default 1): names are 32 px bold at 1080 px output width. A 1080 px wide video on a phone screen is shown about 2.8× smaller, which brings that down to ~11 pt. - Reach by kind of place (
labelReach, defaultLABEL_REACH): a town within 1,000 m (the point of a town is its centre and the track may pass along its edge), a village 400 m, a hamlet 250 m, a peak 250 m, your own point (kind: 'waypoint') 1,500 m. Pass one number for everything, or only some kinds:labelReach: { village: 800 }. - Pace (
labelMinGap, default 0.6 s): when places come in quick succession (a cluster of hamlets in a fast flight), the less important ones are left out. Towns always stay.0shows all. - The place the track starts in is visible from the first frame.
- Where labels would overlap, the more important one wins, then the one passed earlier. They cross-fade instead of swapping abruptly; near the edge of the picture a label fades out.
- In the overview shots at both ends of a flight only towns remain — and the start and finish.
- Start and finish (
keepEndpointLabels, default true): the nearest village, hamlet or town withinendpointRadius(3000 m) of the first and of the last point of the track stays like a landmark, in the overviews too. Distance to the end point decides: a ride that ends after an out-and-back to another village finishes where its last point is. A loop shows its place once. - Your own markers: a label can have its own
color(the dot) andicon(a short text or emoji before the name), e.g.{ name: 'Sněžka', kind: 'peak', color: '#f97316', icon: '▲', priority: 5 }. Withpriority4 or more a label is a landmark: never thinned out and kept in the overviews.
On the Tolmin–Koper track (253 places from OpenStreetMap around it), 68 places are within reach. In version 0.2 a 60 s fly-over showed 31 of them and the 24 s static view 19.
fetchPlaceLabels(points) reads town, village, hamlet and peak names from vector tiles in the
OpenMapTiles schema (layers place and mountain_peak), by default from
OpenFreeMap: free, no key, served from a CDN, works for any basemap
(the tiles are only downloaded for the names). It runs in browsers and in Node ≥ 22.
import { fetchPlaceLabels, PlaceLabelsError } from 'trail-flyover';
let places;
try {
places = await fetchPlaceLabels(points, { language: 'en' });
} catch (err) {
// Some tiles failed even after a retry; err.labels has what the others gave.
if (err instanceof PlaceLabelsError) places = err.labels; else throw err;
}
flyover.load(points, { labels: places });- Only the tiles within
maxOffTrack(2 km) of the track are downloaded, in parallel: a 50 km ride takes about 15–30 tiles of ~50 kB at zoom 12, in well under a second. Long tracks step down in zoom to stay withinmaxTiles(200). zoom(12): every city, town and village; hamlets too except in the densest areas, where the tiles drop the least important ones. On the Tolmin–Koper track zoom 12 shows 67 of the 68 places Overpass gives (one peak missing); zoom 11 only 41.languageprefersname:{language}and falls back to the local name (the default).kinds(city, town, village, hamlet),peaks(true),concurrency(6),timeoutMs(10000),signal.tiles(a{z}/{x}/{y}template) ortileJsonpoint to another OpenMapTiles source (MapTiler, your own server). The tile requests tell the server roughly where the ride was.- A failure is never silent: a tile that fails twice makes the call throw
PlaceLabelsErrorwithlabels(from the tiles that loaded),failedTilesandtotalTiles. - Show the attribution
OPENFREEMAP_ATTRIBUTION("OpenFreeMap © OpenMapTiles Data from OpenStreetMap") with the video. With a Content Security Policy, allowhttps://tiles.openfreemap.orginconnect-src.
fetchPlaceLabels(points, { source: 'overpass' }) (or fetchOverpassPlaceLabels) asks the
Overpass API instead. Every server it asks receives the bounding box of the track. The default
servers are overpass-api.de (FOSSGIS, Germany), overpass.kumi.systems (Switzerland) and
overpass.private.coffee (Austria); pass your own list in endpoints. Overpass is often
overloaded, answering in tens of seconds or not at all. Apps with their own points of interest
should pass them directly as labels.
| id | Description | Key | Sharing the video | Tested |
|---|---|---|---|---|
esri-satellite |
Esri World Imagery, worldwide (summer imagery) | no | personal, non-commercial | ✅ |
cuzk-ortofoto |
ČÚZK orthophoto, the sharpest in Czechia (summer); Esri underneath beyond the border (fallback) |
no | free (CC BY 4.0) | ✅ |
esri-wayback-2022 |
Esri archive 2022: a real winter capture, but snow only in places (Špičák, Železná Ruda) | no | personal, non-commercial | ✅ |
esri-topo |
Esri topographic map, fast server | no | personal, non-commercial | ✅ |
opentopomap |
OpenTopoMap topographic map; slow server (a tile can take 8 s) | no | free (CC BY-SA) | |
esri-satellite-bw |
black-and-white satellite (the same Esri imagery without colour) | no | personal, non-commercial | ✅ |
esri-light |
black-and-white map: light grey base without labels, terrain as hillshade | no | personal, non-commercial | ✅ |
esri-dark |
dark base with hillshade | no | personal, non-commercial | ✅ |
No built-in basemap needs an API key. A keyed basemap of your own can be added through
BasemapDef.requiresKey and apiKeys. A custom basemap is a plain BasemapDef object (tile URLs,
attribution, colour adjustments). The HUD draws the attribution into the video too. background
is the colour shown where a tile has not arrived yet (fast preview flights); pick one close to the
imagery (dark for satellite), so a gap looks like haze, not a bright patch. Terrain always
comes from AWS Terrain Tiles (Terrarium, free).
The "Sharing the video" column is also in the data (BasemapDef.sharing); the player blocks
nothing, the demo only shows a notice. This is not legal advice, just a summary of the terms I read.
- ČÚZK orthophoto has been open data under CC BY 4.0 since 1 July 2023. "© ČÚZK", which is in the video, is enough. The cleanest choice for Czechia.
- Esri: the terms for static maps (screen captures and the like) allow personal use and promoting your own products with attribution; "commercial monetization" needs permission. Video and social media are not mentioned explicitly. The layers (World Imagery, World Topo Map) are under the Esri Master License Agreement and, according to the terms on the items, are not meant for exporting tiles for offline use; fetching tiles as they are displayed during preview and video export is ordinary viewing. The attribution in the video matches what the services themselves declare.
- Esri in production (to be verified): the developer documentation for the current basemap
services (Basemap Styles, Static Basemap Tiles) requires an ArcGIS Location Platform account and
an access token. The
server.arcgisonline.comURLs used here are not mentioned in it. For a public app with many users I therefore recommend an account and a token, with the basemaps passed as your ownBasemapDefwithrequiresKey; I could not find out from the price list how much is free. - Mapy.com is deliberately not among the basemaps. The API terms (from 1 June 2025, art. 4.6.2) forbid storing, exporting and sharing tiles and outputs, and the attribution requires a clickable logo above the map, which a video cannot have. Exporting video for social media would need written consent from Seznam.cz.
- OpenTopoMap is CC BY-SA, but the server is slow and not meant for bulk downloading.
Sources: Mapy.com API terms, Mapy.com attribution, Esri – static maps, Esri – Static Basemap Tiles, ČÚZK – open data.
Continuous snowy aerial imagery in good resolution does not exist for free: Esri and ČÚZK fly in summer, winter Sentinel-2 has 10 m/px and needs registration. I went through the Esri Wayback archive automatically (199 releases). Only the 2021–2022 releases have a winter capture, and only in places.
Hence the winter filter (snow), which covers any basemap in snow: meadows, fields and roofs
turn white, forests stay dark with hoarfrost and water stays dark. An optional snow line based on
the elevation model leaves the valleys green:
new TrailFlyover(el, { maplibregl, basemap: 'cuzk-ortofoto', snow: { snowline: 900 } });
fly.update({ snow: false }); // offIt works through a custom MapLibre protocol (addProtocol), so it can be switched on over any
basemap. The pixel conversion is a pure function, snowifyPixels, tested in Node.
A typical keyframe camera (the comparison baseline is the previous 3D fly-over of the author's app
TrailMetrics, ported in test/helpers/trailMetricsCamera.ts; TrailMetrics now uses this library)
stutters for these reasons:
| Problem | Cause | Solution here |
|---|---|---|
| Rotation pulses | the heading is blended between 150 keyframes with smoothstep, so the angular velocity drops to zero at every keyframe (~5× per second) | no keyframes: the heading is the tangent of the smoothed path, smoothed again in time and limited to 32 °/s |
| The path has kinks | the centre is interpolated linearly between keyframes taken from raw GPS points | resampling at equal distances and zero-lag Gaussian smoothing, with a window proportional to the camera distance |
| The preview stutters | every frame waits for GeoJSONSource.setData (a worker, irregular timing) |
the track is split into segments revealed through feature-state (synchronous); camera and map.redraw() in the same frame |
| The camera bobs | MapLibre takes the height of the centre from whatever terrain tiles are loaded | camera height from its own, pre-smoothed elevation model; centerClampedToGround: false |
Measured with npm run compare on the real track in test/fixtures:
| track, video | max. yaw acceleration: keyframes → here | path kink p99: keyframes → here |
|---|---|---|
| 121 km (Tolmin–Koper), 30 s | 358 → 16 °/s² | 29° → 1.0° per frame |
| 121 km (Tolmin–Koper), 60 s | 97 → 13 °/s² | 22° → 1.3° |
The intro and outro fly along a van Wijk–Nuij curve (the principle behind flyTo): the long move
happens at height and the zoom-in only near the target. Their length follows the zoom ratio (the
121 km track: 119 km → 7.3 km gets 6 s), so that the logarithmic zoom acceleration stays below
~0.6 /s².
The tip of the trail stays in the frame. The smoothed camera path cuts corners by up to 0.2 of the camera distance. In the 9:16 format that is more than half the width of the picture, so the tip used to leave the frame. Now the camera gently steps aside in such a place (the tip stays within 58 % of the width) and flies 30 % further away in narrow formats. A test checks this for all tracks, cameras and aspect ratios. The flat 2D map does not turn, so its path is smoothed less (0.1 instead of 0.22 of the camera distance) and follows short loops closely.
The overview uses the whole picture. The opening and closing shots normally look in the direction of travel. But when an elongated route would lie across the picture (a north–south route in the Story format), the camera turns by up to 90° so that the route is as large as possible. The turn is spread over the whole intro or outro.
src/core/ pure computation, no DOM (tested in Node)
flightPlan.ts track → flight plan: poseAt(t), distanceAt(t), statsAt(t)
geo.ts projection, resampling, Gaussian smoothing, angles
gpx.ts GPX reader (no DOMParser): track points, name, named waypoints
clean.ts removal of GPS glitches (jumps, 0°/0°), tracks across the 180th meridian
terrarium.ts synchronous elevation model from AWS Terrarium tiles (free, keyless)
urls.ts cutting query strings (API keys) out of error messages
i18n.ts texts of the built-in panel and status messages (en, cs)
src/maplibre/
player.ts TrailFlyover: preview, prefetch, export
basemaps.ts basemaps as data
src/hud/hud.ts place labels, tip of the trail, default stats panel
src/effects/ winter filter (recolouring tiles)
src/export/ frame-by-frame encoding through WebCodecs (mediabunny)
src/extras/ place names from OpenStreetMap (vector tiles or Overpass), optional
The camera is a pure function of time. The flight plan is computed once; then poseAt(t)
returns the position of the camera and its target. Preview and export call the same function, so
the video looks exactly like the preview.
A flight has three phases: an opening overview of the whole route, the flight behind the tip of the trail with a smooth start and stop, and a closing overview with a slight orbit. The overviews are computed exactly: a virtual camera projects every point of the track and a binary search finds the closest distance at which the route fits between the title and the stats panel. A test checks this property for all three aspect ratios.
The core (buildFlightPlan, also with preset: 'topdown' for 2D) can be used without the player,
for example to animate a track in an interactive map through map.jumpTo.
- Distance is the exact sum over the original points of the recording (not over the smoothed path), so it matches what the recording app shows (120.7 km for the Tolmin–Koper test track).
- Moving time (
stats.moving) leaves out the stops;stats.elapsedis the whole recorded time. Tolmin–Koper: 7 h 11 min moving out of 9 h 08 min. The default panel shows moving time. - GPS glitches are removed before any computation: a jump away and back faster than 180 km/h, the point 0°/0°, impossible coordinates, and a lone first or last point far from the track. A jump that does not come back (a paused recording, a train) stays. Without timestamps jumps are not judged.
- Tracks across the 180th meridian and in the southern and western hemispheres work (tested).
- Named waypoints in the GPX (
parseGpx(...).waypoints) can be used directly as labels. - The GPX reader runs in linear time on any input, so a malformed or hostile file cannot freeze the page.
Measured on two tracks that are not part of the repository.
A 128 km track (2.8 km/s over the ground in a 60 s video): rendering a frame with tiles loaded has a median of 6 ms, but in real time the constant stream of new tiles keeps the preview at 30–46 fps (25–38 fps with the winter filter). Export is always frame by frame and smooth. The tile cache is therefore sized by track length (350 + 8 per km, at most 1,500).
A 51 km track:
- Computing one frame (camera, trail, HUD) takes under 1 ms. Rendering in MapLibre with cached tiles has a p95 of 4.9 ms.
- Real-time playback: around 64 fps, 0.4 % dropped frames (over 34 ms).
- The preview renders only at the resolution it is displayed at. Full resolution is switched on for export.
- By default MapLibre keeps only ~85 tiles in its cache (5× the number in view). The player
therefore raises
maxTileCacheZoomLevels, and the defaultmaxTileCacheSizeis 350. With 3,000 playback was slower. - Export 1080×1350, 30 fps, 37.6 s: 84 s of rendering, H.264 High, ~8.6 Mbit/s, no duplicated frames. Every frame waits for all tiles, so the video is not blurry even in a fast flight.
- Export of the Tolmin–Koper track (before the test file was trimmed, 124 km) 1080×1920, 30 fps, 60 s (1,801 frames): 106 s, H.264 High, 12.4 Mbit/s, 93 MB, no frozen frame. Waiting for tiles no longer costs a fixed 60 ms per frame: when nothing is missing, rendering continues at once. Verified on 140 camera jumps; not once was a tile left unloaded.
- Preview of the Tolmin–Koper track (4:5, tiles already in the browser cache): 62 fps, 5.7 % of frames over 25 ms.
- Export needs WebCodecs (Chrome, Edge, Firefox 130+, Safari 16.4+). MP4 with H.264 is preferred, otherwise HEVC, AV1 or VP9 is used.
- Place names: peaks in vector tiles are thinned out by importance, so not every named peak is
there. Apps with their own points of interest should pass them as
labels. - Without hardware video encoding (common on Linux) the browser encodes H.264 in software:
measured 43–60 ms per 1080×1920 frame, so a 30 s video (900 frames) takes at least 40–55 s to
export, however fast the network.
video.stats.encodeshows it. - Mobile devices will need a smaller tile cache and probably a lower export resolution.
- The winter filter runs on the main thread. Moving it to a Web Worker would speed up the first pass on long tracks.
- Very long tracks would benefit from variable speed: slower in the mountains and near the finish, faster on the flat.
Bug reports, ideas and pull requests are welcome; CONTRIBUTING.md says how to get started and what a good change looks like. Issues marked good first issue are a good place to begin.
The library has no server and no accounts. SECURITY.md describes what it sends to third parties and how to report a vulnerability.
The code is under the MIT licence (see LICENSE).
- Dependencies: MapLibre GL JS (BSD-3-Clause), mediabunny (MPL-2.0).
- Map tiles are not part of the project and are subject to their providers' terms (see "Licences and sharing the video"). Elevation model: AWS Terrain Tiles.
- Place names in
test/fixtures/*.places.json: © OpenStreetMap contributors (ODbL), see test/fixtures/README.md. - The GPX file in
test/fixturesis the author's own recording, included as test data. For privacy it starts and ends a kilometre away from the real start and finish, and its date is shifted (the times of day are real).

