Build Different

Planning a Route for Trucks with Waypoint Optimization

Kingsley Ubah
Oct 20, 2022 • Last edit on Oct 28, 20229 min read
Laptop showing TomTom Maps and trucks

If you frequently deliver or travel with your truck to unknown destinations, you’ve most likely experienced what it’s like to be unfamiliar with the city’s road network. So, you may have sought guidance from the locals about the best routes to your destination.

TomTom’s Waypoint Optimization service is one of these local guides, but digital. The service works to optimize the order of a given set of waypoints (destinations) by the fastest route. It includes features like optimizing waypoints for cars and trucks.

Using this service, our location-based applications and services can collect coordinates for notable places and locations from a user. Then, we can display the optimal routes to those destinations from nearest to farthest.

In this tutorial, we’ll create a Vue application and add the TomTom Maps SDK. On the homepage of our app, there will be several gorm inputs for users to provide their starting location and the waypoints they want to optimize. These coordinates will then be sent to the Waypoint Optimization service, which will list them in the optimal order. Finally, our app will display the results on a map.

Prerequisites

To follow this tutorial, ensure you have the following:

  • Node.js and its package manager, npm (version 5.2 or higher)
  • Familiarity with the JavaScript/ES6 syntax and the basics of building apps using Vue.js. This tutorial uses Vite to develop Vue apps.
  • A code editor, such as Visual Studio Code
  • A TomTom developer account. This tutorial will require an API key from your account. It’s free to sign up, and you can make thousands of free requests per day, but you can pay to extend the API limits and add more features, depending on your application requirements.

You can check out the final project code here.

Getting Started

To get started, let’s create a new Vite project via the command-line interface (CLI). To do so, start a terminal on your computer, enter your project directory, and execute the following command:

npm init vite

In response to this command, the CLI requests information about our application, like the project’s name and preferred development language or framework. Name the project tomtom-demo and select Vue as the development framework.

After providing that setup information, a scaffold Vue app is generated for us.

Next, run the following commands to install the necessary dependencies from npm:

cd tomtom-demo
npm install

Wait for the installation to conclude before opening the project folder using a code editor like VS Code. You’ll find a folder structure like that shown in the image below:

image 1

Start the Vite development server by executing the npm run dev command on your terminal. After that, navigate to https://localhost:5173 on your web browser. You’ll see the default Vite page, which is shown below:

image 2

Now that our app has been set up, let’s bring in TomTom’s Map SDK and start adding our code.

Using TomTom’s Map SDK in Vue

As outlined in the Maps SDK overview, there are several ways to integrate the TomTom Maps SDK. In this tutorial, we’ll use CDN version 6.

Go to tomtom-demo/index.html in your code editor. Copy the following code and paste it into the file:

1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <!-- [...] -->
5 <title>Vite + Vue</title>
6 <link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.15.0/maps/maps.css'>
7 </head>
8 <body>
9 <div id="app"></div>
10 <script type="module" src="/src/main.js"></script>
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 </body>
14</html>

With this, we’ll now have access to all of the code in the Maps SDK. Next, we’ll create an HTML form for collecting waypoints from the user.

Create a Form to Collect the Waypoint Sequence from the User

We need two sets of coordinates from the user: the origin, such as a warehouse, and the destination waypoints for which they’d like an optimized route. To collect this information, we’ll create a simple HTML form.

Inside your project’s src/components folder, delete HelloWorld.vue, create a file named Map.vue, and populate it with the following code:

1<template>
2 <form id="sole-form">
3 <!-- Origin where the user is starting from -->
4 <div class="row">
5 <label class="form-label">Your Origin:</label>
6 <div class="col">
7 <input type="text" class="form-control" placeholder="Enter longitude" v-model="waypoints[0].lng">
8 </div>
9 <div class="col">
10 <input type="password" class="form-control" placeholder="Enter latitude" v-model="waypoints[0].lat">
11 </div>
12 </div>
13 <hr>
14
15 <!-- Destinations-->
16 <div class="row">
17 <label class="form-label">Destination 1:</label>
18 <div class="col">
19 <input type="text" class="form-control" placeholder="Enter longitude" v-model="waypoints[1].lng">
20 </div>
21 <div class="col">
22 <input type="password" class="form-control" placeholder="Enter latitude" v-model="waypoints[1].lat">
23 </div>
24 </div>
25 <hr>
26
27 <div class="row">
28 <label class="form-label">Destination 2:</label>
29 <div class="col">
30 <input type="text" class="form-control" placeholder="Enter longitude" v-model="waypoints[2].lng">
31 </div>
32 <div class="col">
33 <input type="password" class="form-control" placeholder="Enter latitude" v-model="waypoints[2].lat">
34 </div>
35 </div>
36 <hr>
37
38 <!-- Add 9 other destinations here -->
39
40 <button @click="getOptimizedRoutes">Submit</button>
41 </form>
42
43 <!-- Map below -->
44<div id='map' class='map'></div>
45</template>

With the code block above, we first created the form responsible for collecting the waypoints the user wants to optimize.

The inputs in the first div element collects the longitude and latitude of the origin, while the remaining inputs collects coordinates of the destinations. Each input has a v-model directive that allows us to access whatever the user types inside the form input in the script section of this component.

Below the form inputs, we added a button element for getting the optimized routes. The last div element in the template is where the map will be loaded into.

Save the Map.vue file and go to your browser to see the form. Here’s what it will look like in your browser:

image 3

Defining the Script

In the previous section, inside Map.vue, we created the HTML markup for our form inside of <templates>, which rendered the form shown above.

Now, below <templates>, create a <script> section. This will contain the component’s JavaScript code. Inside <script>, access the waypoint data using the code below. Note that this will be the form inputs inside the data function.

1<script>
2export default {
3 name: "post-request",
4 data() {
5 return {
6 waypoints: [
7 { lat: '', lng : ''},
8 { lat: '', lng: '' },
9 { lat: '', lng: '' } ,
10 { lat: '', lng: '' },
11 // add up to the same number of input fields in the form
12 ],
13 };
14 methods: {
15 // methods go here
16 }
17 },
18};
19
20</script>

Next, we define our first method, getOptimizedRoutes. First, we construct the data, configure our request with our preferred options, and then include both data and options in the body of the POST request:

1getOptimizedRoutes(e) {
2 e.preventDefault();
3
4 const data = {
5 waypoints: this.waypoints.map((location) => {
6 return {
7 point: {
8 latitude: Number(location.lat),
9 longitude: Number(location.lng),
10 },
11 };
12 }),
13
14 options: {
15 travelMode: "truck",
16 vehicleCommercial: true,
17 traffic: "live",
18 departAt: "now",
19 outputExtensions: ["travelTimes", "routeLengths"],
20 waypointConstraints: {
21 originIndex: 0,
22 destinationIndex: 0,
23 },
24 },
25 };
26
27 const requestOptions = {
28 method: "POST",
29 headers: { "Content-type": "application/json;charset=UTF-8" },
30 body: JSON.stringify(data),
31 };
32
33 // fetch request goes here
34}

It’s worth noting that the traffic parameter’s value can be either historical or live. For other Routing APIs, live traffic data is used by default. The Waypoint Optimization API, in contrast, uses historical data by default. Furthermore, the historical data considers previous traffic jams and road closures during the given travel time window.

Next, we make the POST request to TomTom’s Waypoint Optimization API to get the optimized order of the waypoint sequence that we added in the request body:

1fetch("https://api.tomtom.com/routing/waypointoptimization/1?key=put-your-api-key-here", requestOptions)
2 .then(response => response.json())
3 .then((data) => {
4 // For the markers
5 let markers = []
6 let solution = data.optimizedOrder
7
8 // Get user origin
9 var centerLocation = this.waypoints[0]
10
11 // Hide the form
12 document.getElementById('form').remove()
13
14 // create the map
15 let map = tt.map({
16 key: put-your-api-key-here,
17 container: 'map',
18 center: centerLocation,
19 bearing: 0,
20 maxZoom: 21,
21 minZoom: 1,
22 pitch: 60,
23 zoom: 14,
24 });
25
26 map.addControl(new tt.FullscreenControl());
27 map.addControl(new tt.NavigationControl());
28
29 // other code
30 })

In the code above, the optimized waypoints order is returned. We stored them in a variable, hid the form, created a map focusing on the user’s starting point, and added navigation controls to allow us to navigate the map.

Next, we add markers to our map, which will show the waypoint sequence in the original order given by the user:

1 // Add markers to map
2 this.waypoints.forEach(function (location, index){
3 markers.push(new tt.Marker().setLngLat(location).addTo(map))
4 })

The objective of waypoint optimization is to sequence the provided waypoints by the fastest route. To optimize the waypoints the user provides, we call the map() method on the array of optimized waypoints. We create a popup text for each waypoint showing its order in the optimized sequence, which we add using the code below. Note that based on how our code is structured, the first location sent to the API will always be the user’s starting point, which has an index of 0.

1 let optimizedLocs = solution.map((order, index) => {
2 if(order === 0) {
3 const popup = new tt.Popup({ offset: 50 }).setText("Origin")
4 markers[order].setPopup(popup)
5 } else {
6 const popup = new tt.Popup({ offset: 50 }).setText("Destination #" + index)
7 markers[order].setPopup(popup)
8 }
9
10 return this.waypoints[order]
11 })

In the code above, we first checked to see if the current location in the optimized array is the starting point of the journey. Once confirmed, the code inside the if block will run, which creates a popup with the text “Origin” and adds the text to its corresponding marker on the map. This tells the user that the location is their starting point.

(Note: With the Waypoint Optimization API, setting a specific origin isn’t mandatory if the use case doesn’tt require one.)

Now, save the file. Go to src.App.vue and import (and register) the Map component:

1<script setup>
2import Map from './components/Map.vue'
3</script>
4
5<template>
6 <Map/>
7</template>

Then, start your dev server with the following command:

npm run dev

Now, visit http://127.0.0.1:5173/ on your web browser and add the coordinates for a starting point and several nearby destinations in the form. Click Submit. If you don’t have the coordinates handy, use the coordinates found in the coordinates.txt file.

The map should emerge and should contain markers for each location. Click on the markers to learn which destination comes first, then continue through to the last!

image 4

Next Steps

In this article, we used the TomTom Waypoint Optimization in our Vue app to optimize the order of waypoints retrieved from the user’s form inputs. We then displayed the optimized order of the locations to the user by adding the order number in the popup text for each marker on the map.

Moreover, TomTom Maps SDK and other APIs easily be integrated with other web frameworks such as React, Angular, and even plain JavaScript.

Do you want to add top-tier map features to your application? Sign up for a free TomTom Developer account and get started with TomTom’s Waypoint Optimization API!

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