osrmroute
v1.1.0
Published
Official JavaScript/TypeScript SDK for the OSRMRoute Maps, Routing & Geocoding API
Maintainers
Readme
osrmroute
Official JavaScript / TypeScript SDK for the OSRMRoute Maps, Routing & Geocoding API.
- Zero dependencies — uses the platform
fetch(Node 18+, Deno, Bun, browsers) - TypeScript declarations — typed options and common routing/geocoding responses; other results are dynamic
- Routing and geospatial APIs — routing, matrix, isochrones, geocoding, VRP, elevation, geofencing…
[lat, lon]for point helpers — these helpers convert to OSRMlon,lat; raw VRP arrays are the exception described below- Automatic retries with exponential backoff, honouring
Retry-After
npm install osrmrouteQuick start
import { OSRMRoute } from 'osrmroute';
const maps = new OSRMRoute({ apiKey: process.env.OSRMROUTE_API_KEY });
const r = await maps.route([[40.4093, 49.8671], [40.3777, 49.8920]]);
console.log(`${(r.routes[0].distance / 1000).toFixed(1)} km, ${Math.round(r.routes[0].duration / 60)} min`);Get a free key at osrmroute.com — no card required.
Configuration
new OSRMRoute({
apiKey: 'your-key', // required
baseUrl: '…', // self-hosted / staging (default https://osrmroute.com)
timeout: 30_000, // per-request ms
retries: 2, // retries on 429 / 5xx / network errors
authMode: 'query', // or 'bearer' to send Authorization: Bearer
headers: {}, // extra headers
});A bare string also works: new OSRMRoute('your-key').
Routing
await maps.route([a, b, c], { profile: 'car', geometries: 'geojson', steps: true });
await maps.matrix([a, b, c]); // { durations, distances }
await maps.directions([a, b], { alternatives: true, lang: 'az' });
await maps.trip([a, b, c]); // travelling-salesman order
await maps.match(gpsTrace); // snap a noisy trace to roads
await maps.nearest(a, { number: 3 });
await maps.snap([a, b]);
await maps.isochrone(a, { timeLimit: 900 }); // 15-min reachability polygonProfiles: car (global), bike, foot. Aliases driving / cycling / walking also work.
Geocoding
await maps.geocode('Nizami küçəsi, Bakı'); // → { hits: [...] }
await maps.reverse([40.4093, 49.8671]); // coordinates → address
await maps.autocomplete('Berl', { limit: 5 }); // → { suggestions: [...] }
await maps.geocodeBatch(['Baku', 'Tbilisi', 'Yerevan']);
await maps.places([40.4093, 49.8671], { radius: 1000, category: 'restaurant' });Use country for a strict country filter and add city to search only within that city:
await maps.geocode('Nizami', { country: 'AZ' });
await maps.geocode('Nizami', { country: 'AZ', city: 'Bakı' });
await maps.autocomplete('Niz', { country: 'AZ', city: 'Bakı', limit: 5 });country is an ISO 3166-1 alpha-2 code. city requires exactly one country.
Without either filter, search is global. No match returns HTTP 200 with an empty
hits or suggestions list; the API never broadens the search to another area.
Invalid country codes or a city without a country return HTTP 400 with code
InvalidGeocodeFilter and do not consume credits. Records without confirmed city
metadata are excluded when filtering by city. near affects ranking only and
cannot override country/city filters; bbox provides an additional spatial restriction.
These options apply to single geocode and autocomplete requests, not geocodeBatch.
Fleet optimisation
const plan = await maps.optimize({
vehicles: [{ id: 1, start: [49.8671, 40.4093], end: [49.8671, 40.4093] }],
services: [{ id: 1, location: [49.8920, 40.3777] }],
});
await maps.cluster(customers); // group nearby stops into delivery zonesNote: VRP
vehicles/servicestake raw[lon, lat](upstream VROOM format).
Geo utilities
await maps.timezone([40.4093, 49.8671]);
await maps.elevation([[40.4093, 49.8671], [40.3777, 49.8920]]);
await maps.elevationProfile({ points: routePoints });
await maps.boundary([40.4093, 49.8671], { polygon: true });
await maps.geofence(fences, points);
await maps.solar([40.4093, 49.8671], { date: '2026-07-18' });
await maps.geometry('distance', { from: a, to: b });
await maps.convert({ point: [40.4093, 49.8671] });
await maps.country('AZ');Error handling
Every non-2xx response throws an OSRMRouteError:
import { OSRMRoute, OSRMRouteError } from 'osrmroute';
try {
await maps.route([a, b]);
} catch (err) {
if (err instanceof OSRMRouteError) {
if (err.isRateLimited) { /* 429 — plan limit reached */ }
if (err.isOutOfCoverage) { /* 422 — outside routable coverage */ }
console.error(err.status, err.code, err.message);
}
}GET requests and job creation with an explicit stable idempotency key retry transient failures. Other POSTs and cancellation are sent once; a lost response may have an unknown outcome. Never create a fresh job key merely because a response was lost. Retries are limited to 0–5.
Coverage
Availability depends on coordinates, profile and the current dataset. Missing coverage remains explicit; no driving fallback is used for unsupported profiles. Reverse results distinguish detailed addresses from nearby place fallback. Isochrone geometry may be absent when sampling is insufficient. See service status and source metadata; neither implies every road or address is covered.
Version 1.1.0 platform methods
Unknown routing profiles now fail before transport instead of becoming driving.
VRP accepts shipments and a top-level profile; raw VRP location arrays remain
[lon, lat], unlike point helpers. Constraints are verified; global optimality
is not promised. Check unassigned and result quality.
const queued = await maps.createJob('matrix', {
from_points: [[40.4093, 49.8671]], to_points: [[40.3777, 49.8920]], profile: 'car',
}, { idempotencyKey: 'delivery-batch-20261015-001' });
await maps.listJobs();
const status = await maps.getJob(queued.job.id, { result: true });
await maps.cancelJob(queued.job.id); // only a queued job can be cancelled
const sources = await maps.sourceMetadata(); // requires info scope
const fixture = await sandboxMaps.sandbox('geocode', { q: 'Baku' }); // separate sandbox keyThese methods require version 1.1.0 or later. Check the installed version with
npm list osrmroute; a source checkout can be newer than a registry release.
Job states include unknown and expired; these methods never automatically
resubmit an unknown operation. Result retrieval is explicit. Sandbox results are
deterministic fixtures with zero billing, never navigation data. Preserve your
idempotency key across process restarts for the same operation/payload.
License
MIT © MAMMADOFF LLC
