MapScale Docs
Visualizations

A route that looks designed

Casing and accent lines, a dashed alternative, circle markers, fitBounds and a draw-in animation for a route line.

Beginner

What you'll build

A driving route from Siam to Ari that looks designed rather than just plotted: a near-black casing under a cyan accent line with round caps, a dashed amber alternative, start and end markers, a camera that frames both routes, and a line that draws itself in. The route files are real driving routes (GeoJSON LineStrings, the same shape the route API returns), so serve the page over http. Basemap data is © OpenStreetMap contributors.

What you'll build
cd docs/mapscale/visualizations/designed-route
python3 -m http.server 4103
# open http://localhost:4103/

Create the page and keep the basemap quiet

A route only looks designed when the basemap stays quiet underneath it, so roads are near-black greys. The source attribution carries the OpenStreetMap credit.

Create the page and keep the basemap quiet
<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />
	<title>A route that looks designed</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>
	<script>
		maplibregl.addProtocol("pmtiles", new pmtiles.Protocol().tile)

		const map = new maplibregl.Map({
			container: "map",
			center: [100.54, 13.76],
			zoom: 12,
			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]] } },
					},
				],
			},
		})

		// drawTo() from step 5 goes here, before the load handler.
		map.on("load", async () => {
			// Steps 3 to 5 go here.
		})
	</script>
</body>
</html>

Load the routes into GeoJSON sources

Each file is a GeoJSON Feature with a LineString geometry. lineMetrics: true makes MapLibre compute line-progress along the line, which the draw-in animation needs. The dashed alternative goes in first so it sits under the main route, thin and quiet.

Load the routes into GeoJSON sources
const [main, other] = await Promise.all([
	fetch("data/siam-to-ari.geojson").then((r) => r.json()),
	fetch("data/siam-to-chatuchak.geojson").then((r) => r.json()),
])

map.addSource("route", { type: "geojson", data: main, lineMetrics: true })
map.addSource("alt", { type: "geojson", data: other })

map.addLayer({
	id: "alt-line",
	type: "line",
	source: "alt",
	layout: { "line-cap": "butt", "line-join": "round" },
	paint: { "line-color": "#ffb454", "line-width": 3, "line-opacity": 0.8, "line-dasharray": [2, 2] },
})

Add a casing, an accent line and markers

The casing is wider and near-black: it cuts the route out of the roads it follows so it stays readable on same-coloured streets. Round caps and joins stop the line breaking into visible segments at every vertex. Start and end markers are circle layers (no DOM, no images): a white ring around a coloured dot reads as a place, not a vertex.

Add a casing, an accent line and markers
const round = { "line-cap": "round", "line-join": "round" }
map.addLayer({
	id: "route-casing",
	type: "line",
	source: "route",
	layout: round,
	paint: { "line-color": "#05070a", "line-width": 11, "line-opacity": 0.92 },
})
map.addLayer({
	id: "route-line",
	type: "line",
	source: "route",
	layout: round,
	paint: { "line-color": "#35e0ff", "line-width": 4.5 },
})

const coords = main.geometry.coordinates
const end = (kind, i, color) => ({
	type: "Feature",
	properties: { kind, color },
	geometry: { type: "Point", coordinates: coords[i] },
})
map.addSource("ends", {
	type: "geojson",
	data: {
		type: "FeatureCollection",
		features: [end("start", 0, "#ffffff"), end("end", coords.length - 1, "#35e0ff")],
	},
})
map.addLayer({
	id: "ends",
	type: "circle",
	source: "ends",
	paint: {
		"circle-radius": 7,
		"circle-color": ["get", "color"],
		"circle-stroke-color": "#05070a",
		"circle-stroke-width": 3,
	},
})

Frame both routes and draw the line in

fitBounds takes [[west, south], [east, north]]; grow a LngLatBounds point by point and add padding so the route clears any overlay. The draw-in animates a line-gradient stop from 0 to 1: the gradient is the colour up to progress p and transparent after, and line-progress runs 0 to 1 along the line. Animate both the accent and the casing, then drop the gradient so the plain paint takes over.

Frame both routes and draw the line in
// Define once, before the load handler. Stops must be strictly ascending, hence the clamp.
function drawTo(color, clear, p) {
	const q = Math.min(Math.max(p, 0.001), 0.998)
	return ["interpolate", ["linear"], ["line-progress"], 0, color, q, color, q + 0.001, clear, 1, clear]
}

// Inside the load handler, after the layers:
const bounds = new maplibregl.LngLatBounds()
for (const c of coords) bounds.extend(c)
for (const c of other.geometry.coordinates) bounds.extend(c)
map.fitBounds(bounds, { padding: { top: 90, bottom: 60, left: 60, right: 60 }, duration: 0 })

const t0 = performance.now()
const total = 2500 // ms
const tick = (now) => {
	const p = Math.min((now - t0) / total, 1)
	const e = 1 - (1 - p) ** 3 // ease-out cubic
	if (p < 1) {
		map.setPaintProperty("route-line", "line-gradient", drawTo("rgba(53,224,255,1)", "rgba(53,224,255,0)", e))
		map.setPaintProperty("route-casing", "line-gradient", drawTo("rgba(5,7,10,0.92)", "rgba(5,7,10,0)", e))
		requestAnimationFrame(tick)
	} else {
		map.setPaintProperty("route-line", "line-gradient", undefined)
		map.setPaintProperty("route-casing", "line-gradient", undefined)
	}
}
requestAnimationFrame(tick)

Fetch a live route and where to go next

To use the live API instead of the files, create a key at mapscale.io and call the route endpoint. coordinates is lng,lat;lng,lat and profile is driving or walking (cycling returns 400). Auth via the ?key= query parameter is supported (an x-api-key header or a Bearer token also work). The response is { code: "Ok", routes: [{ distance (m), duration (s), geometry: GeoJSON LineString }] }, so the geometry drops straight into the route source. The complete tested page is docs/mapscale/visualizations/designed-route. Keep © OpenStreetMap contributors visible.

Fetch a live route and where to go next
const url =
	"https://api.mapscale.io/v1/route" +
	"?coordinates=100.53391,13.74601;100.54447,13.77969" +
	"&profile=driving&key=pk_test_your_key_here"
const resp = await fetch(url)
if (!resp.ok) throw new Error("route request failed")
const res = await resp.json()
const route = res.routes[0]
map.getSource("route").setData({ type: "Feature", properties: {}, geometry: route.geometry })

On this page

Analytics settings