Travel-time rings with isochrones
Draw nested drive-time rings around a point, translucent and toggleable, from files or from the MapScale isochrone API.
Intermediate
What you'll build
Nested drive-time rings (8, 15, 23 and 30 minutes) around Asok in Bangkok on a dark basemap, with a legend that toggles each ring. An isochrone is a polygon of everywhere reachable within N minutes. The example reads vendored Valhalla output from data/<minutes>.json, so serve it over http (fetch does not work from file://). The last step swaps in the live API. Basemap data is © OpenStreetMap contributors.
cd docs/mapscale/visualizations/isochrones
python3 -m http.server 4102
# open http://localhost:4102/Create the page and a dark basemap
The same keyless pmtiles:// basemap, trimmed to land, water and roads so the rings stay the focus. The legend is a plain div that step 5 fills in. The source attribution carries the OpenStreetMap credit.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Travel-time rings</title>
<style>
html,
body,
#map {
height: 100%;
margin: 0;
}
</style>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.css" />
<script src="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.js"></script>
<script src="https://unpkg.com/pmtiles@4/dist/pmtiles.js"></script>
</head>
<body>
<div id="map"></div>
<div id="legend" style="position:absolute;top:12px;left:12px;z-index:1;background:rgba(10,13,18,0.85);color:#cfe7ff;font:12px/1.6 ui-monospace,monospace;padding:8px 10px;border-radius:6px"><b>Drive time</b></div>
<script>
maplibregl.addProtocol("pmtiles", new pmtiles.Protocol().tile)
const map = new maplibregl.Map({
container: "map",
center: [100.5602, 13.7373], // Asok junction, Bangkok
zoom: 10.4,
minZoom: 4,
style: {
version: 8,
glyphs: "https://maps.thaipropertiesnetwork.com/{fontstack}/{range}.pbf",
sources: {
ms: {
type: "vector",
url: "pmtiles://https://maps.thaipropertiesnetwork.com/thailand-v2.pmtiles",
attribution: "© OpenStreetMap contributors · MapScale",
},
},
layers: [
{ id: "background", type: "background", paint: { "background-color": "#0a0d12" } },
{ id: "landuse", type: "fill", source: "ms", "source-layer": "landuse", paint: { "fill-color": "#0e1219" } },
{ id: "water", type: "fill", source: "ms", "source-layer": "water", paint: { "fill-color": "#0c141f" } },
{
id: "roads",
type: "line",
source: "ms",
"source-layer": "transportation",
filter: ["==", "$type", "LineString"],
paint: { "line-color": "#1b232e", "line-width": { base: 1.2, stops: [[11, 0.5], [18, 10]] } },
},
],
},
})
map.on("load", async () => {
// Steps 3 to 5 go here.
})
</script>
</body>
</html>Load the isochrone polygons
Each file in the example is a GeoJSON FeatureCollection with one polygon whose properties are { contour: <minutes>, metric: "time" }. Merge them into one collection and sort the largest contour first. Layers added later draw on top, so sorting makes the small rings sit above the big ones.
const ORIGIN = [100.5602, 13.7373]
const MINUTES = [8, 15, 23, 30]
// warm (close) -> cool (far), one colour per contour
const RAMP = { 8: "#ffb454", 15: "#ff6b81", 23: "#a06cff", 30: "#35b7ff" }
const files = await Promise.all(MINUTES.map((m) => fetch("./data/" + m + ".json").then((r) => r.json())))
const features = files
.flatMap((fc) => fc.features)
.sort((a, b) => b.properties.contour - a.properties.contour)
map.addSource("iso", { type: "geojson", data: { type: "FeatureCollection", features } })Draw one translucent fill and outline per ring
One fill layer and one line layer per contour, each filtered to its own contour value, in the sorted order. Low opacity lets the basemap and the overlapping rings show through, which gives the heat-map look.
for (const f of features) {
const m = f.properties.contour
map.addLayer({
id: "iso-fill-" + m,
type: "fill",
source: "iso",
filter: ["==", ["get", "contour"], m],
paint: { "fill-color": RAMP[m], "fill-opacity": 0.28 },
})
map.addLayer({
id: "iso-line-" + m,
type: "line",
source: "iso",
filter: ["==", ["get", "contour"], m],
paint: { "line-color": RAMP[m], "line-width": 1.5, "line-opacity": 0.95 },
})
}Add an origin marker, a legend and fit the camera
A marker shows the start point, a checkbox per ring toggles that ring's two layers, and fitBounds frames the biggest ring. The ring geometry can be nested, so the bounds walk recurses until it reaches coordinate pairs.
new maplibregl.Marker({ color: "#ffffff" }).setLngLat(ORIGIN).addTo(map)
const legend = document.getElementById("legend")
for (const m of MINUTES) {
const label = document.createElement("label")
label.style.display = "block"
label.innerHTML = '<input type="checkbox" checked /> ' + m + " min"
label.style.color = RAMP[m]
label.querySelector("input").addEventListener("change", (e) => {
const v = e.target.checked ? "visible" : "none"
map.setLayoutProperty("iso-fill-" + m, "visibility", v)
map.setLayoutProperty("iso-line-" + m, "visibility", v)
})
legend.appendChild(label)
}
// features[0] is the biggest ring (sorted largest first)
const bounds = new maplibregl.LngLatBounds()
const walk = (c) => (typeof c[0] === "number" ? bounds.extend(c) : c.forEach(walk))
walk(features[0].geometry.coordinates)
map.fitBounds(bounds, { padding: 40, animate: false })Go live with the API and where to go next
Instead of files, ask the MapScale API for isochrones anywhere in Thailand. The response is a FeatureCollection; each feature has properties { contour, metric } where metric is "time" (minutes) or "distance" (km), and the geometry is a Polygon or MultiPolygon. Contours must be all minutes (10,20,30) or all km (1km,2km): mixing them returns 400 INVALID_CONTOURS. Use a publishable key in the browser. Reuse the sort and layer loop above, adjusting MINUTES and RAMP to the contours you request. The complete tested page is docs/mapscale/visualizations/isochrones.
async function loadFromApi([lng, lat]) {
const url =
"https://api.mapscale.io/v1/isochrone?point=" + lng + "," + lat +
"&contours=10,20,30&key=pk_test_your_key_here"
const res = await fetch(url)
if (!res.ok) throw new Error("isochrone request failed")
const fc = await res.json()
// Sort by properties.contour descending, then add the layers as above.
return fc.features.sort((a, b) => b.properties.contour - a.properties.contour)
}