Build Different

Find the Quickest Way Through Complicated Routes with TomTom

Spruce Emmanuel
Spruce Emmanuel
Aug 17, 2022 • Last edit on Sep 20, 202212 min read
Laptop screen displaying TomTom map with Waypoint routing

If your end users are fleet managers or are responsible for scheduling deliveries, it’s essential to provide them with the ideal sequences for stops. Without optimizing the stop — or waypoint — sequence, your users’ routes will be less efficient overall, leading to delays, increased costs, and other challenges.

With the TomTom Waypoint Optimization API, planning complicated routes doesn’t have to be a major ordeal. Using this API, we can easily find the most efficient order of stops to make between multiple locations while accounting for factors like traffic, means of travel, and vehicle load. This makes it easier for our end users to plan their routes in advance — which is crucial in the transport industry.

In this tutorial, we’ll build a simple React.js app that uses the TomTom Waypoint Optimization API alongside the TomTom Routing API to find the fastest, most efficient sequence of stops for a route that contains several destinations.

Photo 1

Prerequisites

This uses React.js and the TomTom Waypoint Optimization API, so some knowledge of React and APIs is required to follow along. And, if you don’t already have one, sign up for a TomTom developer account and obtain your API key.

You can find the complete source code for our app here.

Getting Started

To begin, we’ll create a React app. We’ll use the Create React App library, but you can use any React library you want. The methods in this article will work regardless of the library you're using.

In the directory of your choice, open your terminal and run the following:

1# Run this to use npm
2npx create-react-app tom-tom
3# Or run this to use yarn
4yarn create react-app tom-tom
5cd tom-tom
6yarn start

Once the React is up and running, install the packages needed for this tutorial:

1yarn add @tomtom-international/web-sdk-maps
2yarn add @tomtom-international/web-sdk-services
3yarn add from-seconds

Creating the Map

The first step is to create a reusable map component that we will use to display the optimized routes. From inside the src folder, create a new file called Map.js and add the following code:

1function Map({ data, zoom_level, travel_mode }) {
2 return (
3 <div className="map_wrapper">
4 <div className="mapDiv" />
5 </div>
6 );
7}
8export default Map;

Notice that our Map component accepts three props:

  • data — This is an array of objects containing the coordinates of each destination.
  • travel_mode — This indicates the type of vehicle to be used for optimization.
  • zoom_level — This specifies the Map's initial zoom level.

We’ll need to select an element on the DOM to display the map. To do so in React, we'll use the useRef hook:

1import { useRef } from "react";
2
3function Map({ data, zoom_level, travel_mode }) {
4 const mapElement = useRef();
5
6
7
8 return (
9 <div className="map_wrapper">
10 <div ref={mapElement} className="mapDiv" />
11 </div>
12 );
13}
14
15
16export default Map;

Now that we’ve selected the map element on the page, let’s import our map SDK, as well as the useEffect and useState hooks to display our map and manage our state, respectively.

1import "@tomtom-international/web-sdk-maps/dist/maps.css";
2import * as ttservices from "@tomtom-international/web-sdk-services";
3import tt from "@tomtom-international/web-sdk-maps";
4import { fromSeconds } from "from-seconds";
5import { useEffect, useState, useRef } from "react";

Finally, in a useEffect hook, we’ll call our Map method, which will ensure that our map renders whenever the component renders:

1import { useEffect, useState, useRef } from "react";
2
3function Map({ data, zoom_level, travel_mode }) {
4 const mapElement = useRef();
5 const [map, setMap] = useState(null);
6
7
8 const api_key = "your_api_key";
9 useEffect(() => {
10 let map = tt.map({
11 key: api_key,
12 container: mapElement.current,
13 center: [3.319332056, 6.572997708], // Murtala Muhammed Airport
14 zoom: zoom_level,
15 });
16 map.addControl(new tt.FullscreenControl());
17 map.addControl(new tt.NavigationControl());
18 setMap(map);
19 return () => map.remove();
20 }, []);
21
22
23 return (
24 <div className="map_wrapper">
25 <div ref={mapElement} className="mapDiv" />
26 </div>
27 );
28}
29
30
31export default Map;

We keep the entire map object in the map state after the map has been initialized, and we set the state of initialized to true. We do this so that we may add new methods to our map without React throwing an error.

To complete our Map component, we must give it a height and width. Open the scr/ App.css file, and apply the following layout styles:

1body,
2#root {
3 overflow: hidden;
4 height: 100vh;
5 scroll-behavior: smooth;
6}
7.wrapper {
8 display: flex;
9 height: 100%;
10}
11.wrapper_inner {
12 width: 90%;
13 margin: 1rem auto;
14}
15main {
16 overflow-y: auto;
17 flex: 1 0 90%;
18 margin: 1rem 0px;
19}
20aside {
21 background: #36c;
22 color: #fff;
23 text-align: center;
24 flex: 1 0 10%;
25 padding: 1rem;
26}
27.map_wrapper {
28 margin-top: 32px;
29 height: 520px;
30 overflow: hidden;
31}
32.mapDiv {
33 margin-top: 16px;
34 height: 100%;
35}

Now, open the React app in your browser and the map should appear on the page.

Photo 2

Creating Markers

Now, let’s add markers to each location we’ll be delivering to.

The first step is to obtain the coordinates for each of the locations where we will be stopping. These data sets usually come from TomTom’s Route Planners or back-end services:

1const data_set_lagos = [
2 { lng: 3.319332056, lat: 6.572997708, name: "Murtala Muhammed Airport" },
3 { lng: 3.38499846, lat: 6.5166646, name: "University of Lagos - Unilag" },
4 { lng: 3.42166498, lat: 6.416665, name: "Eko Atlantic" },
5 { lng: 3.40083173, lat: 6.499998, name: "Third Mainland Bridge" },
6 { lng: 3.3666652, lat: 6.4499982, name: "Apapa" },
7 { lng: 3.450664864, lat: 6.434831594, name: "Palms Shopping Mall" },
8 { lng: 3.3999984, lat: 6.4499982, name: "EAS Airlines Flight 4226" },
9 { lng: 3.416831666, lat: 6.442998228, name: "Dodan Barracks" },
10 ];

We have different locations in Lagos, Nigeria listed above. We need to pass this data as a prop to our Map component. Make the following changes to src > App.js:

1import Map from "./Map";
2function App() {
3 const data_set_lagos = [ // coordinates ];
4 return (
5 <div className="wrapper">
6...
7 <main>
8 <div className="wrapper_inner">
9 <div id="lagos">
10 <Map data={data_set_lagos} zoom_level={11} travel_mode="truck" />
11 </div>
12 </div>
13 </main>
14 </div>
15 );
16}
17export default App;

After we’ve passed the data to our Map component, we need to store it in a state in our Map.js file:

1...
2import { useEffect, useState, useRef } from "react";
3
4function Map({ data, zoom_level, travel_mode }) {
5 ...
6 const [waypoints] = useState(data);
7 ...
8}
9
10
11export default Map;

Next, we can use another useEffect hook to call our map object. Whenever the maps load, we call a function called create_marker, which will make a marker for each of our locations:

1useEffect(() => {
2 if (map) {
3 map.on("load", () => {
4 waypoints.forEach((location) => {
5 create_marker(location);
6 });
7 });
8 }
9 }, [map]);

The only difference between this and the first useState is that this one is called anytime the initialized state is updated.

So, let’s create the create_marker function:

1function create_marker(location) {
2 const marker_el = document.createElement("div");
3 marker_el.id = travel_mode;
4 const popup = new tt.Popup({ offset: 20 }).setText(location.name);
5 const marker = new tt.Marker({ element: marker_el, anchor: "bottom" })
6 .setLngLat([location.lng, location.lat])
7 .setPopup(popup)
8 .addTo(map);
9
10 return marker;
11 }

As you can see, the create_marker() function only takes one argument — the location.

We create a div element with an id equal to travel_mode and use CSS to create the icon for each marker using that location:

1#truck {
2 background-image: url("url_of_icon");
3 background-size: cover;
4 width: 32px;
5 height: 32px;
6}

With the addition of markers, our preview now looks like this:

Photo 3

Optimizing the Route

The ability to take a set of up to 50 coordinates and provide the best possible waypoint order based on the options specified is where the TomTom Waypoint Optimization API shines. To optimize our route, we need to send the following POST request to the Waypoint API:

1let URL = `https://api.tomtom.com/routing/waypointoptimization/1/best?key=${api_key}`;
2const optimize_routes = () => {
3 const data = {
4 waypoints: waypoints.map((location) => {
5 return {
6 point: {
7 latitude: location.lat,
8 longitude: location.lng,
9 },
10 };
11 }),
12 options: {
13 travelMode: travel_mode,
14 vehicleMaxSpeed: 0,
15 vehicleCommercial: true,
16 vehicleLoadType: ["otherHazmatGeneral"],
17 traffic: "live",
18 departAt: "now",
19 outputExtensions: ["travelTimes", "routeLengths"],
20 waypointConstraints: {
21 originIndex: 0,
22 destinationIndex: 0,
23 },
24 },
25 };
26 fetch(URL, {
27 method: "POST",
28 headers: { "Content-type": "application/json;charset=UTF-8" },
29 body: JSON.stringify(data),
30 })
31 .then((response) => response.json())
32 .then((data) => {
33 console.log(data);
34 })
35 };

You can see above that we’re sending the waypoints (coordinates) along with a lot of options, which help the Waypoint API pick the best possible way to optimize our routes.

Please see the Waypoint Optimization API documentationfor further information on each option, as well as extra options that can be added.

Following the POST request, the API will return an optimized route order and details about each route in that optimized order. We can then reorder our original waypoints using the new returned order:

1let URL = `https://api.tomtom.com/routing/waypointoptimization/1/best?key=${api_key}`;
2const optimize_routes = () => {
3 const data = {
4// options
5 };
6 fetch(URL, {
7 method: "POST",
8 headers: { "Content-type": "application/json;charset=UTF-8" },
9 body: JSON.stringify(data),
10 })
11 .then((response) => response.json())
12 .then((data) => {
13 const optimized_locations = data.summary.legSummaries.map((summary) => {
14 return { ...waypoints[summary.originIndex], ...summary };
15 });
16 console.log(optimized_locations);
17 })
18 };

Updating the Markers

We now have our optimized route and some information about each destination, such as the overall distance from one location to the next and the time it will take to arrive at the next destination.

Let’s display this information as popups on the marker we created earlier. Make the following changes to the Map.js file:

1let URL = `https://api.tomtom.com/routing/waypointoptimization/1/best?key=${api_key}`;
2const optimize_routes = () => {
3 const data = {
4// options
5 };
6 fetch(URL, {
7 method: "POST",
8 headers: { "Content-type": "application/json;charset=UTF-8" },
9 body: JSON.stringify(data),
10 })
11 .then((response) => response.json())
12 .then((data) => {
13 const optimized_locations = data.summary.legSummaries.map((summary) => {
14 return { ...waypoints[summary.originIndex], ...summary };
15 });
16 optimized_locations.forEach((location, index) => {
17 const start_time = new Date(location.departureTime).toLocaleString();
18 const arrival_time = new Date(location.arrivalTime).toLocaleString();
19 const distance_in_seconds = fromSeconds(
20 location.travelTimeInSeconds
21 ).toHours();
22 const start_at = location.originIndex;
23 const end_at = location.destinationIndex;
24 const popup = new tt.Popup({ offset: 50 }).setHTML(
25 `<div class="popup">
26 <h1>Location ${index}</h1>
27 <br />
28 <p>Current Point: ${waypoints[start_at].name}</p>
29 <p>Departure Time: ${start_time}</p>
30 <p>Next Stop: ${waypoints[end_at].name}</p>
31 <p>Arrival Time: ${arrival_time}<p>
32 <p>Distance To next stop: ${location.lengthInMeters / 1000}(km)</p>
33 <p>Estimated Time To next stop: ${
34 distance_in_seconds.hours
35 } Hours, ${distance_in_seconds.minutes} Minutes</p>
36 </div> `
37 );
38 create_marker(location).setPopup(popup);
39 });
40 })
41 };

Let’s put this to the test by adding a button that calls our optimize_routes function in our src > Map.js file:

1...
2function Map({ data, zoom_level, travel_mode }) {
3...
4 return (
5 <div className="map_wrapper">
6 <button
7 className="btn"
8 disabled={map == null ? true : false}
9 onClick={optimize_routes}
10 >
11 Click here to get optimized route
12 </button>
13
14
15 <div ref={mapElement} className="mapDiv" />
16 </div>
17 );
18}
19export default Map;

Each marker now displays a detailed summary of the location once the popup is updated:

Photo 4

Creating the Route

Apart from just optimizing our routes and showing this information in a popup, we also need to create a route path that links each of our destinations. To do this, we must create our route using TomTom's Routing API, and then add the new route as another layer to our map.

Create a new function called create_route in the Map.js file and add the following code:

1const create_route = (locations) => {
2 ttservices.services
3 .calculateRoute({
4 key: api_key,
5 locations,
6 })
7 .then((routeData) => {
8 const features = routeData.toGeoJson().features;
9 features.forEach((feature, index) => {
10 map.addLayer({
11 id: "route" + index,
12 type: "line",
13 source: {
14 type: "geojson",
15 data: feature,
16 },
17 paint: {
18 "line-color": `red`,
19 "line-opacity": 0.8,
20 "line-width": 6,
21 "line-dasharray": [1, 0, 1, 0],
22 }
23 });
24 });
25 });
26 };

The above code takes our specified waypoints and draws a line for each one. We call this function immediately after we update our markers.

1let URL = `https://api.tomtom.com/routing/waypointoptimization/1/best?key=${api_key}`;
2const optimize_routes = () => {
3 const data = {
4// options
5 };
6 fetch(URL, {
7 method: "POST",
8 headers: { "Content-type": "application/json;charset=UTF-8" },
9 body: JSON.stringify(data),
10 })
11 .then((response) => response.json())
12 .then((data) => {
13 const optimized_locations = data.summary.legSummaries.map((summary) => {
14 return { ...waypoints[summary.originIndex], ...summary };
15 });
16 optimized_locations.forEach((location, index) => {
17 ...
18 create_marker(location).setPopup(popup);
19 });
20
21create_route(optimized_locations); // call the create_route function
22 })
23 };

There is now a line on the map that connects all of the destinations.

Photo 5

Finding the Fastest Path Across Several Destinations

Now that we have our reusable Map component set up, we can use it to determine the fastest path along any complex route. Let's use the cities of Coimbra in Portugal and Mumbai in India as examples.

Open src > App.js and make the following changes

1...
2import Map from "./Map";
3function App() {
4...
5 const data_set_COIMBRA = [
6 {
7 lng: -8.43339493308,
8 lat: 40.2016525267,
9 name: "Monastery of Santa Clara-a-Velha",
10 },
11 { lng: -8.459417, lat: 40.207444, name: "University of Coimbra" },
12 {
13 lng: -8.404665048,
14 lat: 40.201999192,
15 name: "Estádio Cidade de Coimbra",
16 },
17 { lng: -8.4333316, lat: 40.192165898, name: "Quinta das Lágrimas" },
18 { lng: -8.3402069725, lat: 40.2079008351, name: "Rio Mondego" },
19 { lng: -8.422831642, lat: 40.205165846, name: "Old Cathedral of Coimbra" },
20 { lng: -8.683, lat: 40.176, name: "Montemor-o-Velho Castle" },
21 ];
22
23const data_set_Mumbai = [
24 {
25 lng: 72.887351,
26 lat: 19.1611,
27 name: "Film City",
28 },
29 { lng: 72.835496658, lat: 18.926329628, name: "Reserve Bank of India" },
30 {
31 lng: 72.834705,
32 lat: 18.921836,
33 name: "Fozli Mango Museum",
34 },
35 {
36 lng: 72.80583011,
37 lat: 18.967662796,
38 name: "Antilia (building)",
39 },
40 {
41 lng: 72.833589,
42 lat: 18.929681,
43 name: "Bombay Stock Exchange",
44 },
45 { lng: 72.821348, lat: 18.950159, name: "India Tower" },
46 {
47 lng: 72.9092113631,
48 lat: 19.1335144659,
49 name: "Indian Institute of Technology Bombay",
50 },
51 { lng: 72.821496714, lat: 18.925996296, name: "Brabourne Stadium" },
52 { lng: 72.93, lat: 18.95, name: "Elephanta Island" },
53 ];
54
55 return (
56 <div className="wrapper">
57 <aside>
58 <h1>TomTom Waypoint Optimization</h1>
59 <ul>
60 ...
61 <li>
62 <a href="#coimbra">Map of Coimbra, Portuga</a>
63 </li>
64 <li>
65 <a href="#mumbai">Map of Mumbai, India</a>
66 </li>
67 </ul>
68 </aside>
69 <main>
70 <div className="wrapper_inner">
71 ...
72 <div id="coimbra">
73 <Map data={data_set_COIMBRA} zoom_level={10} travel_mode="car" />
74 </div>
75 <div id="mumbai">
76 <Map data={data_set_Mumbai} zoom_level={10} travel_mode="truck" />
77 </div>
78 </div>
79 </main>
80 </div>
81 );
82}
83export default App;

Below is a live preview of the optimized routes for Coimbra.

Photo 6

And that of Mumbai:

Photo 7

Conclusion

When we’re working with many waypoints, orchestrating the best sequence of stops can be challenging. Fortunately, it can be streamlined by using the TomTom Waypoint Optimization API. Once we have determined the best sequence, we’re able to construct an efficient route much more easily — and even in advance.

In this article, we learned how to use this API and React to create a simple app that can be used to find the most efficient sequence of stops to make during a trip that requires many stops. By calculating the fastest route, your users can use your maps to travel more efficiently, boosting productivity and reducing unnecessary costs.

You can learn more about creating efficient routes with TomTom maps by checking out the TomTom Waypoint Optimization API and trying the TomTom Routing API for yourself!

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