A commute-time map
A flat listing, an office move, a clinic's catchment: the question is how far you get in ten, twenty or thirty minutes, and the answer people understand is a shape on a map. An isochrone is that shape. Getting it onto a web map takes three small pieces of work: turning the service's rings into GeoJSON, serving the basemap through your own server, and drawing both with MapLibre GL JS.
The approach
- Three isochrones from
/v1/isochrone, at 30, 20 and 10 minutes, with a cell level chosen for the distance they cover. - GeoJSON: each answer's
polygon— rings of(lat, lon), open, outlines and holes in one list — becomes a MultiPolygon of closed[lon, lat]rings, each hole with its outline, with the budget as a property. - The basemap through your server:
/v1/style.jsonwith its source pointed back at you,/v1/tiles.jsonlikewise, and/v1/tiles/{z}/{x}/{y}passed through. Thevector tiles guide covers that proxy properly; here it is at its smallest. - The page draws the basemap and the three shapes, coloured by budget, beneath the labels.
Isochrones are routing; the style, TileJSON and tiles are platform. The Platform plan includes both. See products and plans.
curl -G "https://api.oslew.com/v1/isochrone" \
-H "Authorization: Bearer $GEO_API_KEY" \
--data-urlencode 'at=19.4326,-99.1332' \
--data-urlencode 'seconds=300' \
--data-urlencode 'level=13'from oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
answer = client.isochrone("19.4326,-99.1332", seconds=300, level=13)import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const answer = await client.isochrone("19.4326,-99.1332", { seconds: 300, level: 13 });HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 296
ratelimit-reset: 1
{
"at": [
19.4326,
-99.1332
],
"snapped": {
"node": 355496,
"lat": 19.432020221186303,
"lon": -99.13343108985583,
"distance_m": 68.87232944392214
},
"seconds": 300,
"level": 13,
"cells": [
{
"cell": 9642761832233959424,
"seconds": 281.3,
"bbox": [
19.420689096751655,
19.455007845688197,
-99.17874350782816,
-99.14569912676049
]
},
{
"cell": 9642761866593697792,
"seconds": 192.1,
"bbox": [
19.421249347442334,
19.455567629601948,
-99.16767178301049,
-99.13462893139146
]
},
{
"cell": 9642762141471604736,
"seconds": 296.5,
"bbox": [
19.445940704223943,
19.480259193598762,
-99.1455329228977,
-99.11249313370506
]
},
{
"cell": 9642762210191081472,
"seconds": 192.4,
"bbox": [
19.433594973351948,
19.467913360473943,
-99.15660158764146,
-99.1235602666477
]
},
{
"cell": 9642762244550819840,
"seconds": 81.8,
"bbox": [
19.421808845778784,
19.456126660986374,
-99.15660158764146,
-99.1235602666477
]
}
],
"polygon": [
[
[
19.468714017066482,
-99.1345465947727
],
[
19.456927032348943,
-99.1345465947727
],
[
19.4563677158633,
-99.14561525951646
],
[
19.444581301476948,
-99.14561525951646
],
[
19.444021517563197,
-99.15668545488549
],
[
19.4434609809067,
-99.16775717970316
],
[
19.431675424876655,
-99.16775717970316
],
[
19.41989015733076,
-99.16775717970316
]
]
],
"engine": "base/hierarchy",
"provenance": {
"name": "overture-transportation",
"release": "2026-08-19.0",
"license": "ODbL-1.0"
},
"took_us": 927
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call. Shortened for the page: cells shows 5 of 24. Shortened for the page: polygon.0 shows 8 of 26.
The point snapped to a road node 69 m away, and everything reachable from it in 300 seconds is listed as level-13 cells, each with its earliest arrival. polygon outlines them: the corners of the cells on the edge of the set, as (lat, lon) pairs. That outline is what the map draws.
The program
A server with no framework: it serves the page, answers /api/reach?at=lat,lon&profile=drivingwith a GeoJSON FeatureCollection, and proxies the basemap under /map/. The key is read fromGEO_API_KEY on the server. Run the TypeScript with npx tsx commute-map.ts; seeclients.
"""A commute-time map: how far 10, 20 and 30 minutes reach from a point,
drawn over the basemap. The browser talks only to this server.
python commute_map.py # then open http://127.0.0.1:8000/
index.html and map.js sit in ./static next to this file.
"""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from oslew import BadRequest, Client, GeoError
client = Client(base_url="https://api.oslew.com") # the key is read from GEO_API_KEY
STATIC = Path(__file__).parent / "static"
FILES = {"/": ("index.html", "text/html; charset=utf-8"), "/map.js": ("map.js", "text/javascript")}
MINUTES = (30, 20, 10) # largest first, so the smallest is drawn on top
LEVEL = {"driving": 13, "cycling": 14, "walking": 15} # coarser cells for a longer reach
answers, tiles = {}, {} # both change only with a new data release
def area(ring):
"""Twice the signed area; its sign is the ring's winding."""
return sum(x0 * y1 - x1 * y0 for (x0, y0), (x1, y1) in zip(ring, ring[1:]))
def inside(point, ring):
x, y = point
hit = False
for (x0, y0), (x1, y1) in zip(ring, ring[1:]):
if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0):
hit = not hit
return hit
def to_geojson(polygon):
"""The service's rings — (lat, lon), open, outlines and holes in one list —
as a GeoJSON MultiPolygon: [lon, lat], closed, each hole with its outline."""
rings = [[[lon, lat] for lat, lon in r] + [[r[0][1], r[0][0]]] for r in polygon if len(r) >= 3]
if not rings:
return None
# Outlines all wind one way and holes the other; the largest ring is an outline.
outward = area(max(rings, key=lambda r: abs(area(r)))) > 0
shapes = [[r] for r in rings if (area(r) > 0) == outward]
for hole in (r for r in rings if (area(r) > 0) != outward):
mid = [sum(c) / (len(hole) - 1) for c in zip(*hole[:-1])]
owner = next((s for s in shapes if inside(mid, s[0])), shapes[0])
owner.append(hole)
return {"type": "MultiPolygon", "coordinates": shapes}
def reach(at, profile):
key = (at, profile)
if key not in answers:
features = []
for minutes in MINUTES:
iso = client.isochrone(at, seconds=minutes * 60, level=LEVEL[profile], profile=profile)
shape = to_geojson(iso["polygon"])
if shape:
features.append({"type": "Feature", "properties": {"minutes": minutes}, "geometry": shape})
answers[key] = {"type": "FeatureCollection", "features": features}
return answers[key]
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
# The basemap asks for absolute URLs; they must be this server's.
origin = f"http://{self.headers['host']}"
try:
if url.path in FILES:
name, kind = FILES[url.path]
return self.reply(200, (STATIC / name).read_bytes(), {"content-type": kind})
if url.path == "/api/reach":
q = parse_qs(url.query)
lat, lon = (float(x) for x in q["at"][0].split(","))
profile = q.get("profile", ["driving"])[0]
if profile not in LEVEL:
return self.send_json(400, {"error": "driving, cycling or walking"})
return self.send_json(200, reach(f"{lat:.4f},{lon:.4f}", profile))
# The tile proxy, at its smallest: see the vector tiles guide.
if url.path == "/map/style.json":
style = client.style_json()
for source in style["sources"].values():
if "url" in source:
source["url"] = f"{origin}/map/tiles.json"
return self.send_json(200, style)
if url.path == "/map/tiles.json":
tilejson = client.tiles_json()
tilejson["tiles"] = [f"{origin}/map/tiles/{{z}}/{{x}}/{{y}}.mvt"]
return self.send_json(200, tilejson)
if url.path.startswith("/map/tiles/"):
z, x, y = url.path.split("/")[3:6]
if not y.endswith(".mvt"):
raise ValueError(y)
key = (int(z), int(x), y)
if key not in tiles:
tiles[key] = client.tiles(*key)
data = tiles[key]
if not data:
return self.reply(204, b"", {}) # nothing stored here: open water, or past the deepest zoom
headers = {"content-type": "application/vnd.mapbox-vector-tile",
"cache-control": "public, max-age=86400"}
if data[:2] == b"\x1f\x8b":
headers["content-encoding"] = "gzip" # stored gzipped; urllib does not unpack it
return self.reply(200, data, headers)
self.send_json(404, {"error": "not found"})
except (KeyError, ValueError):
self.send_json(400, {"error": "at is lat,lon; tiles are /z/x/y.mvt"})
except BadRequest as e:
self.send_json(400, {"error": e.message})
except GeoError as e:
self.log_error("oslew: %s", e)
self.send_json(502, {"error": "the map service did not answer"})
def send_json(self, status, body):
self.reply(status, json.dumps(body).encode("utf-8"), {"content-type": "application/json"})
def reply(self, status, data, headers):
self.send_response(status)
for name, value in headers.items():
self.send_header(name, value)
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()// A commute-time map: how far 10, 20 and 30 minutes reach from a point,
// drawn over the basemap. The browser talks only to this server.
//
// npx tsx commute-map.ts # then open http://127.0.0.1:8000/
//
// index.html and map.js sit in ./static next to this file.
import { createServer } from "node:http";
import type { ServerResponse } from "node:http";
import { readFile } from "node:fs/promises";
import { BadRequest, Client, GeoError } from "@oslew/client";
const client = new Client({ baseUrl: "https://api.oslew.com" }); // the key is read from GEO_API_KEY
const FILES: Record<string, [string, string]> = {
"/": ["index.html", "text/html; charset=utf-8"],
"/map.js": ["map.js", "text/javascript"],
};
const MINUTES = [30, 20, 10]; // largest first, so the smallest is drawn on top
const LEVEL = { driving: 13, cycling: 14, walking: 15 }; // coarser cells for a longer reach
type Profile = keyof typeof LEVEL;
const answers = new Map<string, unknown>(); // both change only with a new data release
const tiles = new Map<string, Uint8Array>();
type Ring = number[][];
// Twice the signed area; its sign is the ring's winding.
const area = (ring: Ring) =>
ring.slice(1).reduce((sum, [x1, y1], i) => sum + ring[i][0] * y1 - x1 * ring[i][1], 0);
function inside([x, y]: number[], ring: Ring): boolean {
let hit = false;
for (let i = 1; i < ring.length; i++) {
const [x0, y0] = ring[i - 1];
const [x1, y1] = ring[i];
if (y0 > y !== y1 > y && x < x0 + ((y - y0) * (x1 - x0)) / (y1 - y0)) hit = !hit;
}
return hit;
}
// The service's rings — (lat, lon), open, outlines and holes in one list —
// as a GeoJSON MultiPolygon: [lon, lat], closed, each hole with its outline.
function toGeoJson(polygon: number[][][]) {
const rings = polygon
.filter((r) => r.length >= 3)
.map((r) => [...r, r[0]].map(([lat, lon]) => [lon, lat]));
if (rings.length === 0) return null;
// Outlines all wind one way and holes the other; the largest ring is an outline.
const outward = area(rings.reduce((a, b) => (Math.abs(area(b)) > Math.abs(area(a)) ? b : a))) > 0;
const shapes = rings.filter((r) => area(r) > 0 === outward).map((r) => [r]);
for (const hole of rings.filter((r) => area(r) > 0 !== outward)) {
const corners = hole.slice(0, -1);
const mid = [0, 1].map((k) => corners.reduce((sum, c) => sum + c[k], 0) / corners.length);
(shapes.find((s) => inside(mid, s[0])) ?? shapes[0]).push(hole);
}
return { type: "MultiPolygon", coordinates: shapes };
}
async function reach(at: string, profile: Profile) {
const key = `${at}|${profile}`;
if (!answers.has(key)) {
const features = [];
for (const minutes of MINUTES) {
const iso = await client.isochrone(at, { seconds: minutes * 60, level: LEVEL[profile], profile });
const geometry = toGeoJson(iso.polygon);
if (geometry) features.push({ type: "Feature", properties: { minutes }, geometry });
}
answers.set(key, { type: "FeatureCollection", features });
}
return answers.get(key);
}
function send(res: ServerResponse, status: number, body: string | Uint8Array, headers: Record<string, string> = {}) {
res.writeHead(status, headers);
res.end(body);
}
const sendJson = (res: ServerResponse, status: number, body: unknown) =>
send(res, status, JSON.stringify(body), { "content-type": "application/json" });
createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
// The basemap asks for absolute URLs; they must be this server's.
const origin = `http://${req.headers.host}`;
try {
if (Object.hasOwn(FILES, url.pathname)) {
const [name, kind] = FILES[url.pathname];
return send(res, 200, await readFile(new URL(`./static/${name}`, import.meta.url)), { "content-type": kind });
}
if (url.pathname === "/api/reach") {
const [lat, lon] = (url.searchParams.get("at") ?? "").split(",").map(Number);
const profile = url.searchParams.get("profile") ?? "driving";
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return sendJson(res, 400, { error: "at is lat,lon" });
if (!Object.hasOwn(LEVEL, profile)) return sendJson(res, 400, { error: "driving, cycling or walking" });
return sendJson(res, 200, await reach(`${lat.toFixed(4)},${lon.toFixed(4)}`, profile as Profile));
}
// The tile proxy, at its smallest: see the vector tiles guide.
if (url.pathname === "/map/style.json") {
const style = (await client.style_json()) as { sources: Record<string, { url?: string }> };
for (const source of Object.values(style.sources)) {
if (source.url) source.url = `${origin}/map/tiles.json`;
}
return sendJson(res, 200, style);
}
if (url.pathname === "/map/tiles.json") {
const tilejson = await client.tiles_json();
tilejson.tiles = [`${origin}/map/tiles/{z}/{x}/{y}.mvt`];
return sendJson(res, 200, tilejson);
}
const tile = /^\/map\/tiles\/(\d+)\/(\d+)\/(\d+\.mvt)$/.exec(url.pathname);
if (tile) {
const key = tile.slice(1).join("/");
if (!tiles.has(key)) tiles.set(key, await client.tiles(Number(tile[1]), Number(tile[2]), tile[3]));
const data = tiles.get(key)!;
if (data.length === 0) return send(res, 204, ""); // nothing stored here: open water, or past the deepest zoom
const headers: Record<string, string> = {
"content-type": "application/vnd.mapbox-vector-tile",
"cache-control": "public, max-age=86400",
};
// Stored gzipped. Node's fetch has already unpacked it; another runtime may not have.
if (data[0] === 0x1f && data[1] === 0x8b) headers["content-encoding"] = "gzip";
return send(res, 200, data, headers);
}
sendJson(res, 404, { error: "not found" });
} catch (e) {
if (e instanceof BadRequest) return sendJson(res, 400, { error: e.message });
if (!(e instanceof GeoError)) throw e;
console.error("oslew:", e);
sendJson(res, 502, { error: "the map service did not answer" });
}
}).listen(8000, "127.0.0.1");The page and its script, the same for either server:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Commute times</title>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.css">
<style>html, body, #map { height: 100%; margin: 0; }</style>
<div id="map"></div>
<script src="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.js"></script>
<script src="/map.js"></script>
</html>// In the browser. Every URL here is your own server's: no key, no API host.
const at = "19.4326,-99.1332"; // lat,lon: the API's order
const map = new maplibregl.Map({
container: "map",
style: "/map/style.json",
center: [-99.1332, 19.4326], // [lon, lat]: MapLibre's order
zoom: 10,
});
map.on("load", async () => {
const reach = await (await fetch(`/api/reach?at=${at}&profile=driving`)).json();
map.addSource("reach", { type: "geojson", data: reach });
const colour = ["match", ["get", "minutes"], 10, "#1a9850", 20, "#fdae61", 30, "#d73027", "#888888"];
// Under the first label layer, so street names stay readable.
const labels = map.getStyle().layers.find((layer) => layer.type === "symbol")?.id;
map.addLayer({ id: "reach-fill", type: "fill", source: "reach",
paint: { "fill-color": colour, "fill-opacity": 0.25 } }, labels);
map.addLayer({ id: "reach-edge", type: "line", source: "reach",
paint: { "line-color": colour, "line-width": 1.5 } }, labels);
});The decisions in it
The level: fine enough to read, coarse enough to send
level sets the cell size the reachable roads are binned into: 13 is about 1.2 km, 14 (the default) about 600 m, 15 about 300 m; it is clamped to 8–16. The search itself is quick — a ten-minute isochrone takes about a millisecond — but the answer lists every cell, and each level finer is about four times as many. The program uses 13 for driving, where thirty minutes crosses a city; 14 for cycling; 15 for walking, where thirty minutes is a couple of kilometres and 1.2 km blocks would say little. Seecells and levels.
seconds defaults to 600 and is clamped to 1–3,600, so an hour is the longest budget. Each budget is its own request and its own token; three bands cost three.
From rings to GeoJSON
The rings need four things done to them before a map will draw them as intended:
- Swap the order. The service writes
(lat, lon); GeoJSON is[lon, lat]. - Close them. A ring comes back open — its last corner is not a repeat of its first — and a GeoJSON ring must end where it starts.
- Tell outlines from holes. Both arrive in one list. Outlines all wind one way and holes the other, and the largest ring is always an outline, so the sign of each ring's area sorts them.
- Give each hole its outline. A GeoJSON polygon is an outline followed by its own holes. The program puts each hole with the outline that contains the average of its corners.
Where two reached cells touch only at a corner, the outline can pass through that corner once or be split there, and which one you get can differ from one call to the next. The area covered is the same either way; do not compare or hash the rings between calls.
Cells: arrival times, not shapes
Each cell carries seconds, the earliest arrival anywhere in it, so one thirty-minute answer holds enough to shade by time. But its bbox is not the cell: it is a box padded to be sure of holding the cell, about three cells across — the first box above spans 0.034° of latitude, some 3.8 km, for a cell about 1.2 km across — and neighbouring boxes overlap. Draw polygon, one request per band.
The basemap, through your server
A tile URL carries no credential, the service sends no CORS headers, and the key cannot go to the browser, so the map is served from your own origin:
- The style and the TileJSON point back at whoever asked: the service builds their URLs from the request's host. Your server rewrites them to its own absolute URLs, which MapLibre needs.
- Tiles are gzipped as stored. Python's
urllibhands them over still compressed, so the proxy sendsContent-Encoding: gzip; Node'sfetchhas already unpacked them, so the header must not be sent. Both programs check the first two bytes rather than guess. 204means no tile: open water, or deeper than the archive'smaxzoom. Vector tiles are not overzoomed by the service; MapLibre overzooms the deepest one itself, which is why the TileJSON'smaxzoommust reach the browser.- Every tile is a request on the platform rate, and a map that pans asks for dozens. The programs keep each tile in memory and send
Cache-Controlso the browser keeps it too; in production, put a cache in front.
Drawing
The three shapes nest — the 30-minute area contains the 20 — so they go in largest first and are filled at a quarter opacity: the centre, reached within every budget, comes out darkest. A match onminutes colours them, and both layers are inserted beneath the first symbol layer so street names stay readable.
What to watch out for
- Coordinate order, twice.
atislat,lon; MapLibre'scenteris[lon, lat]. See conventions. http://from the Host header is right for the local run. Behind a proxy that ends TLS, build the origin from your public URL, or the page will ask for tiles over plain HTTP.- Fonts. The style's
glyphsURL points at MapLibre's public demo font server, which the browser fetches from directly. For production, host the glyphs yourself and rewrite that URL too. - Attribution. The basemap and the roads the isochrones are computed from are ODbL-1.0 data; keep MapLibre's attribution control, and see data and licensing before you store or publish the shapes.
- Cell ids are 64-bit integers. A JavaScript number does not print them digit for digit; if you keep them, read them with a parser that preserves 64-bit integers.
- Coverage. An isochrone reaches only as far as the road data loaded for the area; a point more than 9 km from any road is refused with
no road within 9 km. Seeisochrones.
Endpoints
/v1/style.jsonplatformA MapLibre GL style over the basemap: layers, colours and the source pointing back at this service.
/v1/tiles.jsonplatformThe TileJSON 3.0 document for the basemap: the tile URL template, the zoom range, the bounds and the attribution.
/v1/tiles/{z}/{x}/{y}platformOne basemap tile. y may carry an extension: .mvt or .pbf for the vector tile as stored, .png to rasterise it here.