A courier leaves the Medina of Tunis for Carthage. He reads Arabic faster than French, the trip goes through eight roundabouts between Avenue Habib Bourguiba and Carthage, and your app shows him half-translated English instructions. Result: one phone call to the customer, then another.
In this post we'll display a complete route with the TMaps routing API: the line on a Leaflet map, the distance, the travel time, and turn-by-turn instructions in French, Arabic or English. Every number below comes from real requests on the Tunisian road graph.
Try it live: examples.tmaps.tn/07-directions. Drag the A and B markers, change the profile, or switch the instructions to Arabic.
Step 1: a route in one request
GET /routing/direction takes a start point from and an end point to, both as lat,lng:
curl "https://api.tmaps.tn/routing/direction?from=36.7992,10.1709&to=36.8528,10.3261&steps=true&geometry=geojson&language=en&api_key=YOUR_API_KEY"
The response (geometry and steps trimmed):
{
"distance": 19761,
"duration": 2027,
"geometry": {
"type": "LineString",
"coordinates": [[10.170977, 36.800419], [10.170762, 36.800676], "…"]
},
"bbox": [10.170376, 36.799178, 10.325869, 36.858573],
"has_toll": false,
"has_ferry": false,
"legs": [
{
"distance": 19761,
"duration": 2027,
"from": { "lat": 36.7992, "lng": 10.1709 },
"to": { "lat": 36.8528, "lng": 10.3261 },
"steps": ["…"]
}
]
}
Distances are in metres and durations in seconds: 19.8 km and about 34 minutes by car. has_toll and has_ferry tell you whether the trip uses a toll road or a ferry, and bbox is the route's extent ([min_lng, min_lat, max_lng, max_lat]) for framing the map.
Three parameters matter most for display:
-
steps=trueadds the instructions inlegs[].steps. Without it you only get the line and the totals. -
geometry=geojsonreturns the route as a GeoJSONLineStringthat Leaflet draws with no polyline decoder. The default is a lighter encoded polyline. -
language(fr,aroren) sets the language of the instructions and of the street names.
Step 2: reading legs and steps
A route is split into legs, one per pair of consecutive points. With two points there's just one. Each leg has its steps, and each step starts with a maneuver:
{
"instruction": "At the roundabout, take the 2nd exit onto Avenue Habib Bourguiba (RN9)",
"maneuver": {
"type": "roundabout",
"location": { "lat": 36.800043, "lng": 10.185953 },
"bearing_before": 109,
"bearing_after": 131,
"exit": 2
},
"name": "Avenue Habib Bourguiba",
"ref": "RN9",
"distance": 58,
"duration": 16
}
-
instructionis the sentence to display, already written in the requested language. -
maneuver.typesays what to do:depart,turn,roundabout,fork,ramp,arrive… Together withmodifier(left,slight_right,sharp_left…), it's all you need to pick an arrow icon. -
exitis the roundabout exit number, andbearing_before/bearing_afterare the heading in degrees before and after the maneuver. -
nameandrefgive the street name and the road number (RN9,RR23…) when they're known.
From the Medina to Carthage, the API returns 27 steps, eight of them roundabouts. A good test for your icon set.
Step 3: drawing the route with Leaflet
Here's the core of the demo. Create an empty GeoJSON layer, then refill it on every request:
const route = L.geoJSON(null, { style: { color: '#2e47f0', weight: 5, opacity: 0.8 } }).addTo(map);
async function directions() {
const a = start.getLatLng();
const b = end.getLatLng();
const url = new URL('https://api.tmaps.tn/routing/direction');
url.search = new URLSearchParams({
from: `${a.lat.toFixed(5)},${a.lng.toFixed(5)}`,
to: `${b.lat.toFixed(5)},${b.lng.toFixed(5)}`,
profile: document.getElementById('profile').value,
geometry: 'geojson',
steps: 'true',
language: document.getElementById('language').value,
api_key: API_KEY,
});
if (document.getElementById('avoid-tolls').checked) url.searchParams.set('avoid', 'tolls');
const res = await fetch(url);
const data = await res.json().catch(() => ({}));
// … error handling, see step 7
render(data);
}
function render(data) {
route.clearLayers().addData(data.geometry);
map.fitBounds(route.getBounds(), { padding: [40, 40] });
const steps = data.legs.flatMap((leg) => leg.steps ?? []);
// … show the distance, the travel time and the list of steps
}
Watch the coordinate order: GeoJSON is [lng, lat], while Leaflet works in [lat, lng]. L.geoJSON converts for you, and route.getBounds() saves you from flipping bbox by hand. The markers are draggable, and every dragend recalculates the route.
Step 4: instructions in Arabic
With language=ar, the instructions are written in Arabic, and so are the street names when the map has them in Arabic. The same trip, in all three languages:
en |
fr |
ar |
|---|---|---|
| Turn right onto Rue Sidi Sridek | Tournez à droite sur Rue Sidi Sridek | انعطف يمينًا إلى شارع سيدي سريديك |
| At the roundabout, take the 1st exit onto Route de La Goulette (RR23) | Au rond-point, prenez la 1re sortie sur Route de La Goulette (RR23) | في الدوار، اسلك المخرج الأول إلى طريق حلق الوادي (RR23) |
| You have arrived at your destination, on the right | Vous êtes arrivé à destination, à droite | لقد وصلت إلى وجهتك، على يمينك |
To be honest about it: when a street has no Arabic name on the map, the API shows its Latin-script name. On this trip, the Arabic departure instruction reads انطلق نحو الشمال الغربي على Rue Ettoumi. It works the other way round too: a street only known by its Arabic name keeps that name in a French or English response.
So a single instruction can mix both scripts. Don't hard-code the text direction, let the browser decide for each line:
const list = document.getElementById('steps');
list.replaceChildren(...steps.map((step) => {
const li = document.createElement('li');
li.dir = 'auto'; // Arabic first means right to left, Latin means left to right
li.textContent = step.instruction;
return li;
}));
The first strong character decides: the Arabic instruction aligns right even with Rue Ettoumi at the end, and road numbers like (RR23) stay where they belong.
Step 5: the right profile, and roads to avoid
profile accepts driving (the default), walking, cycling, truck and scooter. From the Medina to Carthage:
| Profile | Distance | Time |
|---|---|---|
driving |
19.8 km | 34 min |
truck |
19.8 km | 34 min |
scooter |
19.8 km | 36 min |
cycling |
19.1 km | 1 h 06 |
walking |
16.9 km | 3 h 19 |
For couriers on two wheels, use scooter. In town it's close to the car, but from Tunis to Sousse it takes 140 km and almost 4 hours with no toll, where the car takes the A1 motorway.
avoid excludes roads: tolls, highways, ferries or unpaved, comma-separated. Tunis → Sousse (from=36.8002,10.1815&to=35.8256,10.6084):
| Request | Distance | Time | has_toll |
|---|---|---|---|
| no option | 145.9 km | 1 h 55 | true |
avoid=tolls |
151.5 km | 3 h 05 | false |
avoid=highways |
151.9 km | 3 h 37 | false |
It's a hard exclusion, not a preference. If no route exists without those roads, the API won't make one up: Sfax → Kerkennah with avoid=ferries returns 404 NO_ROUTE.
Step 6: departure time, arrival time, several stops
Pass departure_time in Tunis local time and the response includes the arrival time:
departure_time=2026-12-01T08:30 → "arrival_time": "2026-12-01T10:24"
arrival_time=2026-12-01T10:00 → "departure_time": "2026-12-01T08:05"
With arrival_time, the API works out when to leave. departure_time=now starts from the current time. Durations come from the usual speeds on each road: the API doesn't take live traffic into account yet.
For a delivery round, add stops with waypoints, separated by | in a GET:
?from=36.7992,10.1709&to=36.8528,10.3261&waypoints=36.8094,10.1400
Medina → Bardo Museum → Carthage comes out at 25.9 km in 51 minutes, in two legs: 4.1 km to the Bardo, then 21.8 km to Carthage. The last step of the first leg is a waypoint maneuver ("You have arrived at your stop"): that's where your app can show "Delivery 1 done". For longer lists, switch to POST with a waypoints array, up to 25 points.
Finally, alternatives=true returns up to two other routes in alternatives[]. From the Medina to Carthage, the API suggests one at 18.1 km, shorter but about thirty seconds slower. The array is absent when there's no relevant alternative, which is the case for Tunis → Sousse.
Step 7: handle errors by their code
Every error has the same shape, {"error": {"code": "...", "message": "..."}}. Check code rather than the HTTP status: NO_ROUTE and OUT_OF_COVERAGE are both 404, but they don't call for the same message.
const MESSAGES = {
NO_ROUTE: 'No route matches these options. Try without "avoid tolls".',
OUT_OF_COVERAGE: 'This point is too far from any road. Move the marker.',
LIMIT_EXCEEDED: '25 points at most per route.',
INVALID_REQUEST: 'Invalid request.',
};
if (!res.ok) {
const code = data.error?.code;
if (code === 'ENGINE_ERROR' || code === 'ENGINE_TIMEOUT') return retryLater();
throw new Error(MESSAGES[code] ?? data.error?.message ?? res.statusText);
}
A few real cases:
- a point in Paris:
404 OUT_OF_COVERAGE, "a point is too far from any road usable with this profile"; - 26 points in a POST:
413 LIMIT_EXCEEDED, "at most 25 waypoints per request"; -
alternatives=truewith a departure time:400 INVALID_REQUEST.
ENGINE_ERROR (502) and ENGINE_TIMEOUT (504) come from the routing engine, and they're the only errors worth retrying.
Known limits today
To be upfront about what the API doesn't do yet:
- No live traffic.
departure_timeandarrival_timegive you a schedule based on usual speeds. Today, a trip at 3 am and at 8:30 am has the same duration. - Street names are only in the requested language when the map has them in that language. Otherwise you'll see the other script, like
Rue Ettoumiinside an Arabic instruction. - Some roads have no name on the map. The instruction then becomes "Turn left", or uses the road number ("Turn left onto RN9").
- Every roundabout produces two steps,
roundaboutthenroundabout_exit. If your list feels too long, merge them when you display it. -
alternatives=trueonly works with exactly two points and no departure or arrival time.
To sum up
-
GET /routing/directionwithfrom,to,steps=trueandgeometry=geojson: the line and the instructions in one request. - Read
legs[].steps:instructionfor the text,maneuver.typeandmodifierfor icons,exitfor roundabouts. -
language=arfor Arabic instructions, anddir="auto"on every line. - Pick the right
profile, and useavoidknowing it's a hard exclusion. -
departure_timeorarrival_timefor schedules,waypointsfor rounds,alternativesto offer another way. - Handle errors by
error.code, and only retry engine errors.
Going further
- TMaps for delivery and e-commerce
- Live demo: examples.tmaps.tn/07-directions
- Source code, MIT licensed: github.com/tmaps-tn/tmaps-snippets
- Postman collection: postman.com/tmaps-tn/tmaps-api
- Every parameter and response field: the Directions API documentation
Which language do your couriers or customers want their directions in? Tell us in the comments, or write to us at support@tmaps.tn.


Top comments (0)