Build Different

Routing Truck Rest Stops with TomTom Maps

Lisha Li
Jul 27, 2021 • Last edit on Sep 20, 20229 min read

Most map applications track routes from a start address to a destination address, which only gives you the route and time. TomTom’s Maps SDK for Web provides comprehensive APIs to allow you to build map applications with many exciting features. For example, we can create a truck routing application for truck drivers to choose rest stops after a specified driving time.

TomTom’s developer portal provides live functional examples. We can build our application based on existing examples that already have the essential functions we need.

This tutorial reviews how to build the truck routing application based on the Supporting Points example in CodePen. The Supporting Points example displays the best route between two points and allows adding stops by clicking on the map. To meet the needs of our use case, we can simply use the Reachable Range API to display a vehicle-reachable range within the specified time for the start point and each supporting point that the user picks.

Follow the tutorial in this article to build an application in CodePen and see the results immediately inside CodePen’s live editor. The only thing you need is a browser.

Getting Started

First, let’s do a little bit of housekeeping. We will need a TomTom developer account. If you don’t have one, register an account with TomTom.

Log into the TomTom Developer Portal and get an API key for the Map Display API, Search API, and Routing API.


Once you get your API key, do the following:

This opens the CodePen online live editor with all the HTML, CSS, and JS code. We’ll use this as a starting point and build as we go. But, if you’d like to peek at the final application, you can find it here.

Calculating a Route

We can start interacting with the Supporting Points example by entering the start and the destination addresses. The map displays a route. We can then click on the map to add supporting points.


The Supporting Points example calculates the best route between the start point and the destination point, passing through supporting points using the function. The markers are added using the tt.Marker function.

Adding UI Items

The Supporting Points example already has the input fields for the start and destination addresses. What we need is to add a time input field and a button to submit its value.


In the HTML box, add the following code before the </header> tag:

1<div class= "tt-timeinput">
2 <label class='tt-label'>Driving Time Interval</label>
3 <input id='timebudget' class='tt-input' type='number' value='2000'>
4 </div>
5 <div class='tt-spacing-top-24'>
6 <input id='submit-button' type='submit' class='tt-button -primary tt-spacing-top-24' name='submit' value='Find Region'>
7 </div>

Also change the result header text from “Supporting Points” to “Rest Stops” for our use case. To do so, find <div class='result-header'>Supporting Points:</div>, and change it to <div class='result-header'>Rest Stops:</div>.

Add the following code at the end of the CSS box. The code formats the Driving Time Interval input field:

1 .tt-label{
2 width:160px
3 }
4 .tt-timeinput{
5 align-items: center;
6 display: flex;
7 margin-top: 12px;
8 }

Finding a Region

Next, enter a desired driving time interval in seconds, then click Find Region to see the reachable region overlaid on the map.


Use Calculate Reachable Range to find the reachable region within the time interval of the origin. To do so, provide the origin and the timeBudgetInSec parameters to the function:

  • The origin parameter is a pair of longitude and latitude lines for the “origin point.”
  • The timeBudgetInSec parameter is the maximum driving time interval in seconds.

The request returns a JSON object that contains a polygon boundary in counterclockwise orientation and the precise polygon center (the result of map-matching the “origin point”). We can add a map layer that fills the polygon with the desired color and opacity with the returned results. We define the handleServiceResponse and the drawPolygon functions to handle this.

Add the following JavaScript code at the end of the JS box:

1function handleServiceResponse(serviceData, response) {
2 var bounds = new tt.LngLatBounds();
3 var groupedResponseData = {};
4 response.batchItems.forEach(function(polygonData, i) {
5 var locationData = serviceData[i];
6 var polygon = polygonData.toGeoJson();
9 if (!Array.isArray(groupedResponseData[locationData.location])) {
10 groupedResponseData[locationData.location] = [];
11 }
12 groupedResponseData[locationData.location].push({
13 locationData: locationData,
14 polygon: polygon
15 });
16 polygon.geometry.coordinates[0].forEach(function(point) {
17 bounds.extend(tt.LngLat.convert(point));
18 });
19 });
20 drawPolygon(groupedResponseData);
21 map.fitBounds(bounds, { padding: 50 });
22 }
25 function drawPolygon(groupedResponseData) {
26 Object.keys(groupedResponseData).slice().reverse().forEach(function(locationName, i) {
27 var locationData = groupedResponseData[locationName];
28 var polygonLayers = [];
31 locationData.forEach(function(data, i) {
32 map.addLayer({
33 'id': locationName,
34 'type': 'fill',
35 'source': {
36 'type': 'geojson',
37 'data': data.polygon
38 },
39 'paint': {
40 'fill-color': '#006967',
41 'fill-opacity': 0.7
42 }
43 });
44 polygonLayers.push({
45 id: locationName,
46 color: '#006967'
47 });
48 });
49 layersOnTheMap[locationName] = polygonLayers;
50 var polygonMarker = new tt.Marker().setLngLat(OriginPoint[locationName]).addTo(map);
51 polygonMarker.setPopup(new tt.Popup({ offset: 30 }).setText(locationName));
52 polygonMarker.getElement().addEventListener('click', function() {
53 layersOnTheMap(function(layer) {
54 map.setPaintProperty(, 'fill-color', '#006967');
55 map.setPaintProperty(, 'fill-opacity', 0.5);
56 });
57 });
58 markersOnTheMap.push(polygonMarker);
59 polygonMarker.togglePopup();
60 });
61 }

Users can then pick a rest stop within the polygon or anywhere they want. The map displays the rest stop address when clicking on it. This recalculates the route from the origin to the chosen rest stop.


When users select their first stop location in the Rest Stops section and click Find Region again, the map no longer shows the reachable region. To do this, we must define a cleanMap function for it.

Add the following JavaScript code at the end of the JS box:

1 function cleanMap() {
2 Object.keys(layersOnTheMap).forEach(function(layerGroudKey) {
3 layersOnTheMap[layerGroudKey].forEach(function(layer) {
4 map.removeLayer(;
5 map.removeSource(;
6 });
7 });
8 layersOnTheMap = {};
9 markersOnTheMap.forEach(function(marker) {
10 marker.remove();
11 });
12 markersOnTheMap = [];
13 }

Recalculate the reachable region using the new location. Use the new location as the “origin point” to calculate the new reachable area and overlay it on the map.

Add the following JavaScript code at the end of the JS box:

1 var OriginPoint = {'Origin Point':route.start};
2 var errorHint = new InfoHint('error', 'bottom-center', 5000).addTo(document.getElementById('map'));
3 var loadingHint = new InfoHint('info', 'bottom-center').addTo(document.getElementById('map'));
4 var layersOnTheMap = {};
5 var markersOnTheMap = [];
7 document.getElementById('submit-button').addEventListener('click', function(e) {
8 e.preventDefault();
9 errorHint.hide();
10 loadingHint.setMessage('Loading...');
11 cleanMap();
13if (markerSelected){
14OriginPoint = {'Origin Point':[markerSelected._lngLat.lng,]};
16OriginPoint = {'Origin Point':[startMarker._lngLat.lng,]};
19 var serviceData = [];
21timeBudget: {time: document.getElementById('timebudget').value, color: "#006967"},
22origin: OriginPoint['Origin Point'],
23location: "Origin Point"
27 batchMode: 'sync',
29 batchItems: {
30 return {
31 timeBudgetInSec: data.timeBudget.time,
32 origin: data.origin
33 };
34 })
35 }).then(function(response) {
36 handleServiceResponse(serviceData, response);
37 loadingHint.hide();
38 }).catch(function() {
39 loadingHint.hide();
40 errorHint.setMessage('There was an error with the request, please try again');
41 });
42 });

You’ll need to insert your own API key after key: as noted in the code above.

Removing a Region

Users can pick the next rest stop and so on until they finally reach their destination.


Remove the last reachable region and keep all the rest stops on the map. To do so, add another button to remove the reachable area. Users can also use this button to remove the reachable area at any time.

In the HTML box, add the following code right after the “Find Region” input tag:

<input id='submit-button-clear' type='submit' class='tt-button -primary tt-spacing-top-24' name='submit-clear' value='Remove Region'>

Add the following JavaScript code at the end of the JS box:

1 document.getElementById('submit-button-clear').addEventListener('click', function(e) {
2 e.preventDefault();


And that’s it! We’ve just created a truck routing application in CodePen. Now, you can play with it. If you haven’t looked at the final application in CodePen yet, you can find it here.

In this tutorial, you have learned how to create a truck routing application that allows truck drivers to pick rest stops within a specified driving time. You can see how easy it’s to make an application based on an existing example in TomTom’s developer portal. To see other examples of a reachable region, check out Reachable Region and Batch Reachable Region.

For more information about the APIs used in this use case, including additional options and capabilities, you can review the documentation about Search API, Routing API, and Map Display API at any time.

Get the developer

No marketing fuff. Tech content only.
Thanks for contacting us

We will reach out to you soon.
Blog cards
tomtom tech news