Using MapRanger
Our goal is to let anyone add route planning to a map without running a routing server. MapRanger computes routes in the browser using OpenStreetMap roads and paths. The browser fetches the tiles it needs from a static PMTiles archive, and the same archive supports different cycling profiles.
Install
The package is not on npm yet. Inside this repository it is the mapranger workspace package. Anywhere else, install a tarball:
git clone git@github.com:alvasilvao/mapranger.git
cd mapranger
npm install
npm pack --workspace core # writes mapranger-0.1.0.tgz
# then, in your project
npm install /path/to/mapranger/mapranger-0.1.0.tgzRoute
This runs in a browser with any bundler that supports module workers, such as Vite:
import { createRouter } from 'mapranger';
// The bucket lists its files, newest first.
const { releases } = await (await fetch('https://data.mapranger.xyz/releases.json')).json();
const file = releases.find(key => key.startsWith('routing/world/')) ?? releases[0];
const archiveUrl = 'https://data.mapranger.xyz/' + file;
const router = createRouter({
manifestUrl: archiveUrl.replace('roads.pmtiles', 'manifest.json'),
archiveUrl
});
const route = await router.route({
start: { lon: 6.1296, lat: 49.6116 },
goal: { lon: 6.148, lat: 49.6 },
snapRadius: 250,
profile: 'shortest',
algorithm: 'astar',
diagnostics: true
});
if (route.path) console.log(route.distance, 'metres');
else console.log('No route between these points');
router.close(); // when done: stops the workerA result has path (graph nodes), edgePath, distance in metres, cost and the snapped ends. Bicycle routes also have coordinates to draw. Keep one router per archive: it caches tiles between routes.
Profiles and limits
Profiles: shortest, road-bike, gravel, shortest-bike, exclude-tolls, paved-driving, fastest, cycle-routes. Changing a profile never needs a new archive.
import { createRouter, standardProfiles, LIMIT_PRESETS } from 'mapranger';
const profile = structuredClone(standardProfiles['road-bike']);
profile.cost.surfaceMultiplier.gravel = 1.1;
const router = createRouter({ manifestUrl, archiveUrl, limits: LIMIT_PRESETS.desktop });
const controller = new AbortController();
await router.route({ start, goal, profile }, { signal: controller.signal });Limits are on by default, with the mobile preset. Set any to null to turn it off.
| Key | Limits | Mobile | Desktop |
|---|---|---|---|
maxDistanceKm | Straight-line distance, km | 100 | 300 |
maxArchiveBytes | Downloaded, MB | 100 | 250 |
maxTotalBytes | Downloaded with prefetch, MB | 150 | 375 |
maxArchiveRequests | Range requests | 275 | 1,100 |
maxTilesDownloaded | Tiles downloaded | 250 | 1,000 |
maxStates | Search states | 1,000,000 | 2,500,000 |
maxTimeMs | Time, seconds | 60 | 60 |
Errors
A route that cannot exist resolves with path: null. Cancelling rejects with an AbortError. Every other failure rejects with a RoutingError whose code is one of these. category says whose problem it is, retryable whether the same request may work later.
| Code | Category | Retry | Meaning |
|---|---|---|---|
invalid_request | request | no | The request is malformed. |
invalid_coordinate | request | no | A coordinate is not a longitude and latitude (latitude at most ±85°). |
invalid_snap_radius | request | no | snapRadius must be more than 0 and at most 1000 metres. |
invalid_endpoint | request | no | An endpoint is neither a coordinate, a node key nor an edge position on that node. |
unknown_node | request | no | A node key given as an endpoint is not on the graph for this profile. |
unsupported_profile | request | no | That profile does not exist or is not valid. |
unsupported_algorithm | request | no | That search algorithm does not exist. |
no_snap | map | no | No road the profile can use near the point, or only roads cut off from the network (details.reason "isolated"). |
resource_limit | limit | no | A route limit stopped the route: details.limit says which. |
unsupported_data | data | no | The archive or manifest is in a format or schema this router does not read. |
corrupt_tile | data | yes | The archive returned bytes that do not decode. They are not kept, so a retry downloads them again. |
missing_geometry | data | no | The archive has no shape for an edge of the route. |
manifest_request_failed | network | yes | The manifest could not be downloaded. |
archive_unavailable | network | yes | The archive header could not be read. |
tile_unavailable | network | yes | A tile could not be downloaded. |
worker_setup | runtime | yes | The routing worker could not start. |
worker_error | runtime | yes | The routing worker crashed or could not read a message. |
internal_error | runtime | no | An unexpected error inside the router: a bug to report. |
Published data
The routing files MapRanger publishes. The map reads only the parts it needs.
Loading…
Your own data
The builder reads an OpenStreetMap extract (.osm.pbf) and writes routing tiles into roads.pmtiles. The inspector reads each tile directly from that archive by its z/x/y coordinates.
# from the repository root; needs Python 3, pyosmium and numpy
npm run build:archive -- region.osm.pbf artifacts/region --no-source
npm run dev
# open http://127.0.0.1:4173/developer/map?archive=regionTo host it, put roads.pmtiles and manifest.json on any static host that supports byte ranges. Across origins, allow the Range header and expose Content-Range, Content-Length and ETag. Give every build a new URL: replacing a file breaks routers that already have it open. The data is OpenStreetMap's, so publish it under the ODbL with attribution.
Source
Everything is in alvasilvao/mapranger (private for now): core/ is the router and builder, web/ is this site. The core will get its own repository later. The code is MIT licensed.
Open source
MapRanger is built on these projects. Thank you to the people behind them.
Software
| Project | Used for | Licence |
|---|---|---|
| PMTiles | Archive format and range reader | BSD-3-Clause (specification: CC0) |
| fflate | Decompression inside the PMTiles reader | MIT |
| MapLibre GL JS | Maps | BSD-3-Clause |
| pyosmium | Reads OpenStreetMap data in the builder | BSD-2-Clause |
| libosmium | Underneath pyosmium | BSL-1.0 |
| osmium-tool | Filters the planet before a build | GPL-3.0 |
| NumPy | The builder's node arrays | BSD-3-Clause |
| React | Website | MIT |
| TanStack Start and Router | Website framework and routing | MIT |
| Vite | Dev server and bundler | MIT |
| Vite plugin for React | React in Vite | MIT |
| Tailwind CSS | Styles | MIT |
| Cloudflare Workers SDK | Vite plugin and Wrangler | MIT or Apache-2.0 |
| TypeScript | Type checking | Apache-2.0 |
| DefinitelyTyped | Type definitions | MIT |
| Playwright | Browser tests | Apache-2.0 |
Data and map assets
| Project | Used for | Licence |
|---|---|---|
| OpenStreetMap | Roads, tags and restrictions; basemap data | ODbL 1.0 |
| Protomaps basemaps | Basemap schema and tiles | BSD-3-Clause code, CC0 design |
| Natural Earth | Low-zoom basemap data | Public domain |
| Basemapkit | The Avenue map style | MIT |
| Noto Sans | Map fonts | OFL 1.1 |
| OSM Liberty | Map sprite sheet | BSD code, CC BY design |
| Maki | Icons in that sprite sheet | CC0 1.0 |