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.tgz

Route

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 worker

A 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.

KeyLimitsMobileDesktop
maxDistanceKmStraight-line distance, km100300
maxArchiveBytesDownloaded, MB100250
maxTotalBytesDownloaded with prefetch, MB150375
maxArchiveRequestsRange requests2751,100
maxTilesDownloadedTiles downloaded2501,000
maxStatesSearch states1,000,0002,500,000
maxTimeMsTime, seconds6060

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.

CodeCategoryRetryMeaning
invalid_requestrequestnoThe request is malformed.
invalid_coordinaterequestnoA coordinate is not a longitude and latitude (latitude at most ±85°).
invalid_snap_radiusrequestnosnapRadius must be more than 0 and at most 1000 metres.
invalid_endpointrequestnoAn endpoint is neither a coordinate, a node key nor an edge position on that node.
unknown_noderequestnoA node key given as an endpoint is not on the graph for this profile.
unsupported_profilerequestnoThat profile does not exist or is not valid.
unsupported_algorithmrequestnoThat search algorithm does not exist.
no_snapmapnoNo road the profile can use near the point, or only roads cut off from the network (details.reason "isolated").
resource_limitlimitnoA route limit stopped the route: details.limit says which.
unsupported_datadatanoThe archive or manifest is in a format or schema this router does not read.
corrupt_tiledatayesThe archive returned bytes that do not decode. They are not kept, so a retry downloads them again.
missing_geometrydatanoThe archive has no shape for an edge of the route.
manifest_request_failednetworkyesThe manifest could not be downloaded.
archive_unavailablenetworkyesThe archive header could not be read.
tile_unavailablenetworkyesA tile could not be downloaded.
worker_setupruntimeyesThe routing worker could not start.
worker_errorruntimeyesThe routing worker crashed or could not read a message.
internal_errorruntimenoAn 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=region

To 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

ProjectUsed forLicence
PMTilesArchive format and range readerBSD-3-Clause (specification: CC0)
fflateDecompression inside the PMTiles readerMIT
MapLibre GL JSMapsBSD-3-Clause
pyosmiumReads OpenStreetMap data in the builderBSD-2-Clause
libosmiumUnderneath pyosmiumBSL-1.0
osmium-toolFilters the planet before a buildGPL-3.0
NumPyThe builder's node arraysBSD-3-Clause
ReactWebsiteMIT
TanStack Start and RouterWebsite framework and routingMIT
ViteDev server and bundlerMIT
Vite plugin for ReactReact in ViteMIT
Tailwind CSSStylesMIT
Cloudflare Workers SDKVite plugin and WranglerMIT or Apache-2.0
TypeScriptType checkingApache-2.0
DefinitelyTypedType definitionsMIT
PlaywrightBrowser testsApache-2.0

Data and map assets

ProjectUsed forLicence
OpenStreetMapRoads, tags and restrictions; basemap dataODbL 1.0
Protomaps basemapsBasemap schema and tilesBSD-3-Clause code, CC0 design
Natural EarthLow-zoom basemap dataPublic domain
BasemapkitThe Avenue map styleMIT
Noto SansMap fontsOFL 1.1
OSM LibertyMap sprite sheetBSD code, CC BY design
MakiIcons in that sprite sheetCC0 1.0