Show a traffic layer
Show a traffic layer
Draw Navvo traffic on every road of your map. Each road and direction has an answer: measured where recent measurements exist, the road's typical traffic where its own history is strong enough, and expected traffic everywhere else. Every line says which of the three it is, so your users can always tell a measurement from an estimate. Uses Traffic.
Scope required: traffic
Recommended: the traffic tiles
GET /traffic/tiles/{z}/{x}/{y}.mvt serves vector tiles your map loads like any other vector source: no tile-cover call, no merging. Each line carries level, ev (what it is based on), cls (road class) and dir (which direction of a two-way road).
const KEY = 'nvvo_YOUR_KEY';
// One URL per 5-minute slot: the tiles are cacheable, and a new slot brings new traffic.
const slot = () => new Date(Math.floor(Date.now() / 300000) * 300000).toISOString();
const tiles = () => [`https://navvo.io/api/v1/traffic/tiles/{z}/{x}/{y}.mvt?t=${encodeURIComponent(slot())}`];
const map = new maplibregl.Map({
container: 'map',
style: `https://navvo.io/api/v1/tiles/style?style=standard&api_key=${KEY}`,
// send the key with the traffic tiles too
transformRequest: (url) => (url.includes('/traffic/tiles/') ? { url, headers: { 'x-api-key': KEY } } : { url }),
});
const COLOR = ['match', ['get', 'level'], 'slow', '#F9A825', 'heavy', '#E84B36', 'standstill', '#A01A12', '#2DBE60'];
const WIDTH = ['interpolate', ['linear'], ['zoom'], 6, 1, 10, 2, 13, 3, 16, 5, 19, 8];
// From z15 the two directions of a two-way road sit side by side (each on its right-hand side).
const OFFSET = ['interpolate', ['linear'], ['zoom'], 14.9, 0, 15, ['*', 1.5, ['get', 'dir']], 18, ['*', 4, ['get', 'dir']]];
const MINOR = ['in', ['get', 'cls'], ['literal', ['minor', 'service']]];
const SORT = ['match', ['get', 'level'], 'standstill', 3, 'heavy', 2, 'slow', 1, 0];
map.on('load', () => {
const before = map.getStyle().layers.find((l) => l.type === 'symbol')?.id; // keep labels on top
map.addSource('navvo-traffic', { type: 'vector', tiles: tiles(), minzoom: 6, maxzoom: 14 });
// Non-colour cue: a white casing under roads measured recently.
map.addLayer({ id: 'traffic-measured-casing', type: 'line', source: 'navvo-traffic', 'source-layer': 'traffic',
filter: ['all', ['==', ['get', 'ev'], 'observed'], ['!', MINOR]],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: { 'line-color': '#FFFFFF', 'line-width': ['+', WIDTH, 3], 'line-offset': OFFSET } }, before);
map.addLayer({ id: 'traffic-major', type: 'line', source: 'navvo-traffic', 'source-layer': 'traffic',
filter: ['!', MINOR],
layout: { 'line-cap': 'round', 'line-join': 'round', 'line-sort-key': SORT },
paint: { 'line-color': COLOR, 'line-width': WIDTH, 'line-offset': OFFSET } }, before);
// Minor and service roads only from z15, so a city view stays readable.
map.addLayer({ id: 'traffic-minor', type: 'line', source: 'navvo-traffic', 'source-layer': 'traffic', minzoom: 15,
filter: MINOR,
layout: { 'line-cap': 'round', 'line-join': 'round', 'line-sort-key': SORT },
paint: { 'line-color': COLOR, 'line-width': ['*', WIDTH, 0.6], 'line-offset': OFFSET } }, before);
// Move to the next slot every 5 minutes.
setInterval(() => map.getSource('navvo-traffic').setTiles(tiles()), 300000);
});
- Refresh: the
tparameter pins a 5-minute slot. Change it every 5 minutes (as above) to move to the next slot; within a slot the tiles are cacheable. - Directions: from zoom 15 the two directions of a two-way road sit side by side, each on its right-hand side, so a road that is jammed one way and free the other shows both.
- Minor streets appear from zoom 15, so a city view stays readable.
Legend
| Colour | Level |
|---|---|
#2DBE60 | Free / سلسة |
#F9A825 | Slow / بطيئة |
#E84B36 | Heavy / شديدة |
#A01A12 | Standstill / متوقفة |
| Line | ev | Legend label (en / ar) |
|---|---|---|
| Solid, with a white casing | observed | Measured recently / حركة مرصودة مؤخرا |
| Solid | typical | Typical / حركة معتادة |
| Solid | expected | Expected / حركة متوقعة |
Put the evidence label in the legend and in a tooltip as well as using colour, so the meaning never depends on colour alone. "Measured recently" appears only where at least three independent contributors measured that road recently.
Traffic on a route
To colour a route and give its ETA in traffic, send the route you are drawing to POST /traffic/route with shape and baseSeconds. Every road of the route is taken at the time you reach it, and the answer says what it is based on:
const r = await (await fetch("https://navvo.io/api/v1/traffic/route", {
method: "POST",
headers: { "content-type": "application/json", "x-api-key": KEY },
body: JSON.stringify({ locations, shape, baseSeconds, departureTime: new Date().toISOString() }),
})).json();
// r.segments: GeoJSON coloured by level, each with properties.evidence
// r.traffic.evidence === "observed" ? "Live traffic" : r.traffic.evidenceLabel.en // e.g. "Expected"
Label the route's traffic "Live" only when traffic.evidence is observed.
Showing what a planned route's traffic is based on
A route's traffic block from POST /routing/plan and the segment answers use a finer set of classes, each with its own label and line pattern in the response. Show them, so a driver can tell measured traffic from an estimate:
| Based on | Line | Legend label (en / ar) |
|---|---|---|
Measured traffic (observed, observed_supplied) | solid | Measured recently / حركة مرصودة مؤخرا |
An expected value (forecast) | dashed | Expected / حركة متوقعة |
Usual traffic (typical) | dashed | Typical / حركة معتادة |
Road type only (structural, unknown) | dotted | Limited data / بيانات محدودة |
// Build the legend from the route's own labels.
const { traffic } = plan; // the POST /routing/plan response
if (traffic?.status === "ok") {
for (const [cls, label] of Object.entries(traffic.labels)) {
legend.add({ text: lang === "ar" ? label.ar : label.en, pattern: label.pattern, share: traffic.sourceMix[cls] });
}
}
- Use the label text and
patternfrom the response (labelsin thetrafficblock,labelon each segment part) rather than your own wording, and keep the line pattern in the legend so the meaning never depends on colour alone. - Never show a guessed slow speed as a closure. Only a verified closure is one: an
access: "blocked"segment answer or a road edit.
A summary badge
For a single congestion read-out over an area, GET /traffic/summary returns a congestionScore, dominant level, and a per-level breakdown:
const s = await (await fetch(
"https://navvo.io/api/v1/traffic/summary?bbox=" + bbox, { headers: { "x-api-key": KEY } }
)).json();
// s.conditions.summary -> "Slow moving" (live) or "Usually light traffic at this hour" (no live data)
// s.conditions.summaryAr -> the same in Arabic
Older endpoints
These still work. The traffic tiles above replace them for drawing a layer:
GET /traffic/lines/tiles/{z}/{x}/{y}withGET /traffic/lines/tile-cover: GeoJSON lines for roads with recent measurements only.GET /traffic/predicted/tiles/{z}/{x}/{y}: GeoJSON lines of typical traffic for an hour.GET /traffic/analysed/grid: the usual traffic per map cell, to colour roads yourself.