Build Different

Creating a Real-Time Construction Fleet Planning App with TomTom Maps APIs

Victor Ikechukwu
Jan 13, 2022 • Last edit on Sep 20, 202214 min read
Creating a Real-Time Construction Fleet Planning App with TomTom Maps APIs

This tutorial explores how we can seamlessly use the TomTom Maps APIs to solve our application’s location-related requirements. We’ll build a real-time tracking app to help users manage a construction company’s vehicle fleet.

We’ll see how to use:

  • The Routing API and its Calculate Route method to calculate the possible routes construction vehicles can take to sites based on specific parameters.
  • The Location History API to track the vehicle’s location.
  • The Geofencing API to determine when construction vehicles are close to the site so workers can prepare for their arrival.

We’ll discuss each app feature requirement, why the tools are relevant to the use-case we’re solving, and how to implement them. You just need to know some JavaScript, HTML, and CSS to follow along. We’ll guide you through using TomTom’s tools.

Let’s dive in!

##PREREQUISITES To start using TomTom Maps API, you need an API key. This key will authorize your request to use the service.

Don’t have one yet? Visit How to get a TomTom API key to learn more or sign up for a developer account to get one. Your free developer account provides access to thousands of daily requests and is acceptable for commercial use. Just pay-as-you-grow when your app becomes popular.

SETUP

First, we’ll need to initialize the map and its user interface (UI). The app will comprise two parts: a map on the right, and a sidebar with form controls on the left.

Create an index.html file in a folder on your computer. Then, open the file in a code editor and populate it with this code:

1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <title>Construction Fleet Planning App</title>
8 <!-- Includes SDK's stylesheet -->
9 <link href="https://api.tomtom.com/maps-sdk-for- web/cdn/6.x/6.15.0/maps/maps.css" rel="stylesheet" type="text/css" />
10 <!-- Includes SDK's JavaScript-->
11 <script src="https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.15.0/maps/maps-web.min.js"></script>
12 <script src="https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.15.0/services/services-web.min.js"></script>
13 <!-- CSS styles -->
14<link rel="stylesheet" href="./styles.css" />
15
16 </head>
17 <body>
18 <div class="container">
19 <div class="control-panel">
20 <h2 class="control-panel__title">Construction Fleet Planing App</h2>
21 <form class="control-panel__controls">
22 <fieldset>
23 <label for="start-address" class="">Start Address:</label>
24 <input type="text" class="" placeholder="san diego" id="start-address" />
25 </fieldset>
26 <fieldset>
27 <label for="end-address" class="">End Address:</label>
28 <input type="text" class="" placeholder="lily avenue" id="end-address" />
29 </fieldset>
30 <fieldset>
31 <label for="arrival-time" class="">Estimated Arrival Time:</label>
32 <input type="datetime-local" id="arrival-time" />
33 </fieldset>
34 <fieldset>
35 <label for="explosives-present">Vehicle is carrying explosives:</label>
36 <input type="checkbox" id="explosives-present" value="USHazmatClass1" />
37 </fieldset>
38 <fieldset>
39 <label for="gas-present">Vehicle is carrying compressed gas:</label>
40 <input type="checkbox" id="gas-present" value="USHazmatClass2" />
41 </fieldset>
42 <fieldset>
43 <label for="is-truck">Vehicle is a truck:</label>
44 <input type="checkbox" id="is-truck" value="truck" />
45 </fieldset>
46 <button class="control-panel__btn">Track</button>
47 </form>
48 </div>
49 <div id="map" class="map"></div>
50 </div>
51 </script>
52 <script>
53 const apiKey = "<Your_API_Key>";
54 const SanJose = {lon: -121.867905, lat: 37.279518}
55 const map = tt.map({
56 key: apiKey,
57 container: "map",
58 center: SanJose,
59 zoom: 10,
60 });
61 map.addControl(new tt.FullscreenControl());
62 map.addControl(new tt.NavigationControl());
63</script>

Here, the tt.map constructor creates a map. The container parameter requires the ID of an HTML element containing the map. The center parameter centers the map on San Jose, California, using its longitude and latitude coordinates.

Remember to replace <Your_API_Key> with your API key from your developer account.

Now, include your CSS styles in a styles.css file containing the following code. The top of the HTML file will link to this CSS file.

1*,
2*:before,
3*:after {
4 box-sizing: border-box;
5 padding: 0;
6 margin: 0;
7}
8body {
9 color: #5f5f5f;
10 font-size: 1.1rem;
11}
12.container {
13 width: 100vw;
14 height: 100vh;
15 display: flex;
16}
17.control-panel {
18 width: 30%;
19 box-shadow: 1px 0px 12px 0px #00000067;
20 height: 100%;
21 overflow-x: hidden;
22 overflow-y: auto;
23}
24.control-panel::-webkit-scrollbar {
25 width: 0px;
26 height: 0px;
27}
28.control-panel__title {
29 font-size: 1.8rem;
30 margin: 1rem 0;
31 padding: 1rem;
32 text-align: center;
33 border-bottom: 3px solid #181616;
34 box-shadow: 0px 3px 6px 0px #00000029;
35}
36.control-panel__controls {
37 display: flex;
38 flex-flow: column nowrap;
39 align-items: center;
40 justify-content: space-around;
41}
42.control-panel__controls fieldset {
43 width: 95%;
44 margin: 1.2rem 0;
45 border: 0;
46 display: flex;
47 align-items: center;
48 justify-content: space-between;
49}
50fieldset input {
51 min-width: 58%;
52 outline: none;
53 font-size: 1rem;
54 border: 2px solid #ccc;
55 padding: 0.8rem;
56 border-radius: 8px;
57}
58fieldset input:focus {
59 border: 2px solid #007fff;
60}
61.control-panel__btn {
62 padding: 1rem;
63 font-size: 1.3rem;
64 outline: none;
65 border: none;
66 border-radius: 8px;
67 color: #fff;
68 background: #007fff;
69 width: 45%;
70}
71.map {
72 width: 70%;
73 height: 100%;
74}

Photo 1

You should have a UI similar to the image above. With the setup complete, we can start implementing the app’s feature requirements.

CALCULATING THE ROUTE

Managers can’t identify the best routes construction vehicles should take to arrive and deliver materials on time by simply looking at the map. But early or late arrivals can ruin the materials or cause delays, so route information is vital.

TomTom’s Calculate Route service determines the possible routes between an origin and a destination location, based on specific parameters like the type of vehicle, estimated time of arrival, and the fastest route.

We can find the best routes for construction vehicles to reach the construction site using Calculate Route.

First, we add markers to the origin and destination points on the map, where the LngLat parameter is the longitude and latitude coordinates of these locations. We store each marker in the markers array. This information will come in handy when it’s time to call the calculate route service.

1 //markers array
2 const markers = [];
3 // add marker
4function addMarker(lnglat) {
5 const marker = new tt.Marker().setLngLat(lnglat).addTo(map);
6 markers.push(marker.getLngLat());
7 }

Next, the app has two input fields to get the starting and destination addresses. The app then passes these addresses to the calculate route service. getAddress gets geographical coordinates for these addresses using the Fuzzy Search service, then passes the coordinates to the addMarker function.

1// get the lnglat coordinates of an address
2 async function getAddress(searchValue) {
3 let address = tt.services
4 .fuzzySearch({
5 key: API_KEY,
6 query: searchValue,
7 lon: -121.8863286,
8 lat: 37.3382082,
9 })
10 .then((cordinates) => {
11 // add marker
12 addMarker(cordinates.results[0].position);
13 const { lng, lat } = cordinates.results[0].position;
14 return { lng, lat };
15 });
16return address;
17 }

Now that our app has stored the geographical coordinates, we can call the calculate route service:

1// get the values of the input fields for configuring the calculateRoute service
2 const isTruck = document.getElementById("is-truck").checked
3 ? document.getElementById("is-truck").value
4 : null;
5 const arrivalTime = document.getElementById("arrival-time").checked
6 ? document.getElementById("arrival-time").value
7 : null;
8 const carriesExplosive = document.getElementById("explosives-present")
9 .checked
10 ? document.getElementById("explosives-present").value
11 : null;
12 const carriesGas = document.getElementById("gas-present").checked
13 ? document.getElementById("gas-present").value
14 : null;
15
16 function getRoute(marker) {
17 const routeOptions = {
18 "key": API_KEY,
19 "locations": marker,
20 "arriveAt": arrivalTime,
21 "travelMode": isTruck,
22 "vehicleLoadType": [ carriesExplosive, carriesGas],
23 "vehicleCommercial": true,
24 };
25
26 tt.services.calculateRoute(routeOptions).then(function (response) {
27 console.log(response.toGeoJson());
28 console.log(response);
29 var geojson = response.toGeoJson();
30 map.addLayer({
31 "id": "route",
32 "type": "line",
33 "source": {
34 "type": "geojson",
35 "data": geojson,
36 },
37 "paint": {
38 "line-color": "#4a90e2",
39 "line-width": 8,
40 },
41 });
42
43 var bounds = new tt.LngLatBounds();
44 geojson.features[0].geometry.coordinates.forEach(function (point) {
45 bounds.extend(tt.LngLat.convert(point)); // creates a bounding area
46 });
47 map.fitBounds(bounds, {
48 duration: 200,
49 padding: 50,
50 maxZoom: 13,
51 }); // zooms the map to the searched route
52 });
53 }

In the code above, the tt.services.calculateRoute constructor calls the calculates route service. The constructor receives the routeOptions object containing properties like the type of loads onboard, time of arrival, vehicle type, and the locations property containing the origin and destination LngLat coordinates from the markers array.

Then, the service returns a promise. We’ll tap into this promise to get its response and draw the route’s path on the map.

We need to tell our application to run the code above when the user clicks the Track button.

1document.querySelector(".control-panel__btn")
2 .addEventListener("click", function (e) {
3 e.preventDefault();
4 Promise.all([
5 getAddress(document.getElementById("start-address").value),
6 getAddress(document.getElementById("end-address").value),
7 ])
8 .then((points) => {
9 getRoute(points);
10 })
11 .then(() => {
12 document.querySelectorAll("input").forEach((input) => {
13 input.value = "";
14 input.checked = false;
15 });
16 });
17
18 });

See the result:

GIF 1

ENABLING LOCATION HISTORY

Construction managers need to know where their vehicles are and where they've been. This allows them to allocate assets efficiently and avoid idle equipment. TomTom’s Location History API enables us to store, retrieve, and track device location and movements.

To use the service, you need an admin key and a layer of security to complete API requests to the service.

You can generate an admin key using Postman to send a POST request to https://api.tomtom.com/location/1/register?&key=Your_API_Key with the following body:

1{
2“secret”: "your_secret",
3}

The body of the request takes a secret parameter. This secret is a password you’ll need for making any future configurations, so use a password you can remember and ensure you don't lose it.

A successful response logs your admin key to the console:

1{
2adminKey: your_admin_key
3}

CREATING AN OBJECT

Now, we can create an object representing the item we are tracking, such as a worker, phone, or vehicle.

To create an object, first send a post request to https://api.tomtom.com/locationHistory/1/objects/object?adminKey=Your_Admin_Key&key=Your_API_KEY, with the name of the object in the body:

1{
2 "name": name,
3}

Photo 2

Here’s a link to the request on Postman if you’d like to try it out: Creating an object

The response will contain the object name and ID.

WORKING WITH AN OBJECT’S LOCATION

We can track an object’s location by storing and retrieving its positions from the service to know where it is and where it’s been.

To record an object’s location, you must give the service permission to store an object's position. So, send a Post request to https://api.tomtom.com/locationHistory/1/settings?key=Your_API_Key&adminKey=Your_Admin_Key with a body of:

1{
2 consentForStoringObjectsPositionsHistory: true,
3}

This call is a one-time request enabling storing an object’s location. Now, we can start tracking objects.

To track an object’s location, first, we need to start storing its changing positions as past positions, using the Send position endpoint:

1// send object's location
2function sendPostion(lnglat) {
3 let cordinates = lnglat;
4 // create Json Object to store location
5 let position = {
6 type: "Feature",
7 geometry: {
8 type: "Point",
9 coordinates: [cordinates.lng, cordinates.lat, 0],
10 },
11 object: "Your_Object_ID"
12 };
13 // Use fetch to send the location
14 fetch(
15 "https://api.tomtom.com/locationHistory/1/history/positions?key=Your_Admin_Key ",
16 {
17 method: "POST",
18 headers: {
19 "Content-Type": "application/json",
20 },
21 body: JSON.stringify(position),
22 }
23 ).then((result) => {
24 console.log(result);
25 });
26 }

Now, we can get its past positions for tracking using the get objects position service:

1// get location history
2 function getObjectLocations() {
3const date = new Date().toISOString();
4 fetch(
5 "https://api.tomtom.com/locationHistory/1/history/positions/Your_Object_Id?key=Your_API_Key&adminKey=Your_AdminKey&from="+date+""
6 )
7 .then((response) => response.json())
8 .then((result) => {
9 const lngLatArray = result.positions.features.map(
10 (feature) => feature.geometry.coordinates
11 );
12 console.log(lngLatArray);=
13 lngLatArray.forEach((lngLat) => {
14 addMarker(lngLat);
15 });
16 });
17 }
18
19 document.querySelector(".show-history").addEventListener("click", (e) => {
20 e.preventDefault();
21 getObjectLocations();
22 });

In this code, we add a marker to the map on page load. Every time the marker drags across the map, the code calls the sendPostion function to send the marker’s LngLat position to the location history API.

Then, when the user clicks the show-history button, the app calls the getObjectLocations function to get the object’s position history and render a marker on each of its previous positions.

GIF 2

ENABLING GEOFENCING

TomTom's Geofencing service lets you define and manage virtual borders (geofences) around specified locations. When we combine this geofencing with the Location History API, we can determine an object’s location relative to these virtual barriers. We can then know whether they’re located within, outside, or close to a geofenced area.

The app can notify managers when a vehicle is approaching a geofenced site. This notification enables the managers to ensure the site is ready to receive the vehicle’s contents, such as having workers ready to unload construction materials or use the concrete before solidification.

Just like Location History, Geofencing requires an admin key when accessing the service. However, you can only register one admin key per account, so we’ll use the same admin key we registered with the Location History API.

CREATING A PROJECT

Now that we have our admin key ready, we need to create a project. A project is an object that stores our geofences. We can store hundreds of geofences in a single project.

First, we send a post request to the endpoint to create a project:

https://api.tomtom.com/geofencing/1/projects/project?adminKey<ADMIN_KEY>=&key=<API_KEY>

We include the name of the project as a parameter in the body:

1{
2 "name": "Project_Name"
3}

Photo 3

Here’s a link to the request on Postman if you’d like to try it out: Creating a Project

A successful response logs the project’s ID and name to the console.

CREATING A GEOFENCE

Now that we have created the project, we are ready to start creating geofences. We make a geofence around the construction site to track construction vehicle arrival.

To create a fence, we send a post request to the following:

https://api.tomtom.com/geofencing/1/projects/${projectId}/fence?adminKey=Your_Admin_Key&key=Your_API_Key

Remember to replace {projectId} in the request URL with the project ID you just created.

The request body should contain the following:

1 {
2 "name": "Area 1",
3 "type": "Feature",
4 "geometry": {
5 "type": "Point",
6 "radius": 11361.72744452612,
7 "shapeType": "Circle",
8 "coordinates": [
9 -121.892115,
10 37.331016
11 ]
12 }
13}

The code above contains the details needed to create a fence around a location. The coordinates parameter takes the location’s latitude and longitude, and the shapeType parameter defines the fence’s shape (in this case, a circle). The response logs the request object above to the console, including the provided fence ID.

Now, we can display the geofence on our map:

1function displayFence() {
2 fetch("https://api.tomtom.com/geofencing/1/fences/${fence id}?key=Your_API_Key")
3 .then((response) => response.json())
4 .then((result) => {
5 console.log(result);
6 map.addLayer({
7 id: "san jose",
8 type: "fill",
9 source: {
10 type: "geojson",
11 data: result,
12 },
13 paint: {
14 "fill-color": "blue",
15 "fill-opacity": 0.4,
16 "fill-outline-color": "blue",
17 },
18 });
19 });
20 }
21
22 map.on("load", () => {
23 displayFence();
24 });

The code above calls the displayFence function when the map loads. This function displays the fence by fetching the fence details and drawing the shape on the map.

Remember to replace ${fence id} with your fence ID. The fence should now be visible on the map.

Photo 4

CREATING A TRANSITION ALERT RULE

TomTom’s Geofencing API provides an alert service to notify your app when assets enter or leave geofences. You can use the same object with the Geofencing and Location History APIs interchangeably.

First, you need to create a contact group. The contact group contains subscribed email addresses that will receive notifications from the service.

To set up a contact group, first, send a post request to https://api.tomtom/notifications/groups?key=Your_API_Key with the request body:

1{
2"name": "group_name",
3"webhookUrls" : [],
4"emails": []
5}

The emails and webhooks parameters above will contain a list of URLs and email addresses to receive the messages.

A successful response logs the notification group ID to the console.

Next, send a post request to https://api.tomtom.com/geofencing/1/alerts/rules?key=Your_Admin_Key adminKey=Your_Admin_Key with the body:

1{
2 "name": "Name of alert rule",
3 "project": "Enter id of project to watch or *",
4 "fence": "Id of fence to watch or *",
5 "object": "id of object to watch or *",
6 "alertType": "TRANSITION",
7 "alertRuleConstraints": {
8 "transitionType": "ALL"
9 },
10 "notificationGroup": "id of your notification group",
11 "enabled": true
12}

Now the app will notify the email address and URLs whenever an object enters the fence.

NEXT STEPS

Our construction company users now have a handy app to plan fleet routes, track equipment locations, and receive an alert when a vehicle crosses a geofence and is on its way to the construction site. With all this information, the fleet manager can make the most efficient use of their equipment, ensure materials arrive when expected, and get workers ready to receive the materials — a boost to construction fleet efficiency with TomTom doing most of the heavy lifting.

From here, you can improve the app by including multiple construction sites, sorting equipment by vehicle type, adding authentication to restrict access to managers only, and much more.

Learn more about integrating TomTom’s Maps APIs into your applications to manage your fleets, locate vehicles, and track assets on a map in real-time. Visit the TomTom developer portal and sign up for a free developer account today. Happy mapping!

Get the developer
newsletter.

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

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