How To Schedule Routing for Truck Drivers
Mike Mackrory·May 10, 2019

How To Schedule Routing for Truck Drivers

Mike MackroryMike Mackrory
Mike Mackrory
Mike Mackrory is a Global citizen who has settled down in the Pacific Northwest - for now. By day he works as a Senior Engineer on a Quality Engineering team and by night he writes, consults on several web based projects and runs a marginally successful eBay sticker business. When he’s not tapping on the keys, he can be found hiking, fishing and exploring both the urban and the rural landscape with his kids. Always happy to help out another developer, he has a definite preference for helping those who bring gifts of gourmet donuts, craft beer and/or Single-malt Scotch.
May 10, 2019 · 14 min read

TomTom’s APIs provide developers with simple access to powerful mapping and geolocation solutions. This article shows how to use the TomTom Android SDK to build an application for truck drivers. Specifically, we’ll use the SDK to determine the best route to the destination, and we’ll tell the driver when they need to leave to get there on time.

When the United States Air Force developed the Global Positioning System (GPS), its objective was to enable someone with a GPS receiver to receive geolocation and time information anywhere on or near the earth. It’s obvious how GPS could be useful in a military context. Once GPS technology became available to the public at large, companies like TomTom began leveraging it to do many other useful things, including developing complex consumer applications. And thanks to TomTom’s recent decision to release APIs to developers, integrating GPS technology into complex consumer applications is easier than ever.

TomTom’s APIs provide developers with simple access to powerful mapping and geolocation solutions. The solutions are the result of years of engineering innovation by TomTom, and decades of information about traffic patterns and trends.

To demonstrate how powerful TomTom’s APIs are, this article shows how to use the TomTom Android SDK to build an application for truck drivers. Specifically, we’ll use the SDK to determine the best route to the destination, and we’ll tell the driver when they need to leave to get there on time.

(Note: that this article focuses on the Android SDK, but SDKs are also available for the Web and iOS. Also note that if you prefer, you can connect to the APIs directly from your application, rather than using the SDKs.)

Getting Started

Before we get started you will need to log in to the TomTom Developer portal (or register for a new account). You need to configure an application before you can request an API Key. From your dashboard, click on the “+ Add a new App”button. Applications require a name, and you’ll need to enable the APIs that the application needs to access. For this example, the products we’ll be using are the Search API, the Routing API, and the Map Display API. If you’re following along, select the Search API, Routing API, and Map Display API products and click on Create App. Additionally, we’ll need the Consumer API Key when we configure the TomTom dependencies in our application.

Setting Up your project

I used Android Studio to build this application and began with a blank activity screen. Our object is to build a simple application to demonstrate the following concepts:

  • Address completion with a “fuzzy” search (meaning a search whose results are not limited to the specific keywords or phrases used in the search query, but also extend to related terms)

  • Determining the current location of the device

  • Finding the best route

I’ll include links at the end with more information on each component and a more complex example which you can download, and explore this functionality more comprehensively.

What we’ll do first is create input fields for the driver to enter their destination and arrival time. Once we have that information, we’ll find coordinates of the destination, and determine the best route. We’ll display the time the driver needs to leave and display the route.

The <fragment> at the bottom of the screen has an android:nameof

permissions, access and build configuration

Before we start coding our solution, we need to take care of some administrative tasks. This includes adding the TomTom SDKs as dependencies and setting up device permissions. We’ll start by adding the TomTom repository to our project’s build.gradle file. Locate the allprojects object within the file and add the TomTom repository to this object.

Use the best free HTML tools: read the blog, use the online editor, find the tags.

1    allprojects {
2    repositories {
3        google()
4        jcenter()
5        maven {
6            url ""
7        }
8    }

Now that we can access the repository, open the app’s build.gradle file and add the following dependencies to the dependencies object. While you’re in this file, you’ll also want to make sure that the compileOptions set the Source and Target Compatibility to at least 1.8.

2dependencies {
3    implementation fileTree(dir: 'libs', include: ['*.jar'])
4    implementation ''
5    implementation ''
6    implementation ''
7    implementation ''
8    testImplementation 'junit:junit:4.12'
9    androidTestImplementation ''
10    androidTestImplementation ''

Finally, you need to open the AndroidManifest.xml file and make the following additions. First, add user permission to allow the app access to the device location service.

2uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

Second, add the following meta-data objects to the application object. Ensure that you replace ReplaceWithAPIKey with your API Key.

3    android:name="OnlineSearch.Key"
4    android:value="ReplaceWithAPIKey" />
6    android:name="OnlineMaps.Key"
7    android:value="ReplaceWithAPIKey" />
9    android:name="OnlineRouting.Key"
10    android:value="ReplaceWithAPIKey" />

Now that we have the housekeeping taken care of, it’s time to build out the solution.

Using a Fuzzy Search to Autocomplete the Address

The control for the Delivery Address is an AutoCompleteTextView Object. We can add a listener to this control, which can react to changes to the text, and suggest possible addresses using the SearchAPI.

Let’s start by initializing some helper objects and a couple of constants that we’ll need to use. We’re also going to initialize the TomTom APIs we’ll be using in this example and create an initialization function for them.

2private AutoCompleteTextView txtAddress;
4private List addressAutocompleteList;
5private Map<String, LatLng> searchResultsMap;
6private ArrayAdapter searchAdapter;
7private Handler searchTimerHandler = new Handler();
8private Runnable searchRunnable;
10private SearchApi searchApi;
11private RoutingApi routingApi;
12private TomtomMap tomtomMap;
14private static final int MIN_LEVEL_OF_FUZZINESS = 2;
15private static final int MIN_AUTOCOMPLETE_CHARACTERS = 3;
16private static final int AUTOCOMPLETE_SEARCH_DELAY_MILLIS = 600;
18private void initTomTomAPIs() {
19    searchApi = OnlineSearchApi.create(getApplicationContext());
20    routingApi = OnlineRoutingApi.create(getApplicationContext());
21    MapFragment mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(;
22    mapFragment.getAsyncMap(this);

Let’s look at the constants in more detail. Each of these values can be adjusted to tune how the autocomplete functionality works.

  • MIN_LEVEL_OF_FUZZINESS - A fuzzy search finds exact and similar matches to the text we enter. Different levels of “fuzziness” affect the types of results you get.

  • MIN_COMPLETE_CHARACTERS - We won’t start searching for matches until at least 3 characters have been entered.

  • AUTOCOMPLETE_SEARCH_DELAY_MILLIS - We’ll wait 600ms after a user stops typing before we return results. This delay limits the number of calls to the API and provides a better user experience.

We’ll implement the Autocomplete functionality in two steps. The first step is to configure the autocomplete functionality on the field, and the second step is to create the search function. The autocomplete functionality is boilerplate autocomplete code, and it calls addressAutoComplete,*** ***which we’ll explore next.

2public void configureAutocomplete(final AutoCompleteTextView autoCompleteTextView) {
3    addressAutocompleteList = new ArrayList<>();
4    searchResultsMap = new HashMap<>();
5    searchAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, addressAutocompleteList);
7    autoCompleteTextView.setAdapter(searchAdapter);
8    autoCompleteTextView.addTextChangedListener(new BaseTextWatcher() {
9        @Override
10        public void onTextChanged(CharSequence s, int start, int before, int count) {
11            if (searchTimerHandler != null) {
12                searchTimerHandler.removeCallbacks(searchRunnable);
13            }
14        }
16        @Override
17        public void afterTextChanged(final Editable s) {
18            if (s.length() > 0) {
19                if (s.length() >= MIN_AUTOCOMPLETE_CHARACTERS) {
20                    searchRunnable = () -> addressAutoComplete(s.toString());
21                    searchAdapter.clear();
22                    searchTimerHandler.postDelayed(searchRunnable, AUTOCOMPLETE_SEARCH_DELAY_MILLIS);
23                }
24            }
25        }
26    });
27    autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
28        String item = (String) parent.getItemAtPosition(position);
29        if (autoCompleteTextView == txtAddress) {
30            destination = searchResultsMap.get(item);
31        } else if (autoCompleteTextView == txtAddress) {
32            destination = searchResultsMap.get(item);
33        }
34        hideKeyboard(view);
35    });
38private void hideKeyboard(View view) {
39    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
40    if (in != null) {
41        in.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
42    }
45private abstract class BaseTextWatcher implements TextWatcher {
46        @Override
47        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

You’ll see that we added an ItemClickListener to the Autocomplete functionality. When a user clicks on the address they would like, the response from the API also includes the GPS coordinates. We save these in the destination parameter to use later.

The ***addressAutoComplete ***function takes address text and an AutoCompleteTextView control, and performs a fuzzy search using the TomTom SearchAPI object. We’ll first create the object, using the ApplicationContext, which passes our API Keys from the manifest file. Then, we’ll build a SearchQuery, subscribe to the response, and when it returns, we’ll update the autocomplete list on the text control.

2public void addressAutoComplete(final String address, final AutoCompleteTextView autoCompleteTextView) {
3 FuzzySearchQueryBuilder(address)
4        .withLanguage(Locale.getDefault().toLanguageTag())
5        .withTypeAhead(true)
6        .withMinFuzzyLevel(MIN_LEVEL_OF_FUZZINESS).build()
7    )
8    .subscribeOn(
9    .observeOn(AndroidSchedulers.mainThread())
10    .subscribe(new DisposableSingleObserver() {
11        @Override
12        public void onSuccess(FuzzySearchResponse fuzzySearchResponse) {
13            if (!fuzzySearchResponse.getResults().isEmpty()) {
14                addressAutocompleteList.clear();
15                searchResultsMap.clear();
16                for (FuzzySearchResult result : fuzzySearchResponse.getResults()) {
17                    String addressString = result.getAddress().getFreeformAddress();
18                    addressAutocompleteList.add(addressString);
19                    searchResultsMap.put(addressString, result.getPosition());
20                }
21                searchAdapter.clear();
22                searchAdapter.addAll(addressAutocompleteList);
23                searchAdapter.getFilter().filter("");
24            }
25        }
27        @Override
28        public void onError(Throwable e) {
29            Toast.makeText(MainActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
30        }
31    });

The final step is to add the autocomplete functionality to the text field. Inside the onCreate function, add the following lines.

5txtAddress = findViewById(;

We’ll create the initCurrentLocation function next.

Determining the Current Location

Now that we know where we’re going, we need to know our starting position. We’ll use the current location of the device, giving us a chance to explore the TomTom LocationSource object. Step one is to implement the LocationUpdateListener interface on the Java class. We’ll then create a *LocationSource *object, a *currentLocation *object to store the current location, and a constant to hold the location of the Location Service Permission.

2public class MainActivity extends AppCompatActivity implements LocationUpdateListener {
4    private LocationSource locationSource;
5    private LatLng currentLocation;
7    private static final int PERMISSION_REQUEST_LOCATION = 0;

The LocationUpdateListener interface requires that we implement an onLocationChanged function. We’ll also create a function to initialize the LocationSource and handle the permissions check.

2private void initCurrentLocation() {
3    PermissionChecker permissionChecker = AndroidPermissionChecker.createLocationChecker(this);
4    if(permissionChecker.ifNotAllPermissionGranted()) {
5        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
6                Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_LOCATION);
7    }
8    LocationSourceFactory locationSourceFactory = new LocationSourceFactory();
9    locationSource = locationSourceFactory.createDefaultLocationSource(this, this,  LocationRequest.create()
10            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
11            .setFastestInterval(2000)
12            .setInterval(5000));
13    locationSource.activate();
17public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
18    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
19    switch (requestCode) {
21            if(grantResults.length >= 2 &&
22                    grantResults[0] == PackageManager.PERMISSION_GRANTED &&
23                    grantResults[1] == PackageManager.PERMISSION_GRANTED) {
24                locationSource.activate();
25            }
26            else {
27                Toast.makeText(this, "Location permissions not granted.", Toast.LENGTH_SHORT).show();
28            }
29            break;
30    }
34public void onLocationChanged(final Location location) {
35    currentLocation = new LatLng(location);

The *LocationSource *object enables us access to the Location Service on the Android device. This service returns the GPS coordinates and can be configured to update the app as the location changes. If our app becomes too chatty, we can increase the interval between updates, and even deactivate the LocationSource object. Initialization of the LocationSource object depends on the user granting permission to the app to use the Location Service on the device.

After the *LocationSource *object is activated, the *currentLocation *is updated with the current location. We can use this location, and the location from the destination address to determine a route.

Finding the route

Now that we have our current location, our destination location, and the delivery time, we have everything we need to ask TomTom to create a route for us. We’ll start from the onCreate function and then build out the functions we need from there.

2txtDepartureTime = findViewById(;
3btnScheduleDelivery = findViewById(;
5btnScheduleDelivery.setOnClickListener(v -> {
6    String time[] =  txtDepartureTime.getText().toString().split(":");
7    LocalDateTime deliveryTime = Integer(time[0]), new Integer(time[1]));
8    requestRoute(currentLocation, destination, TravelMode.TRUCK, Date.from(deliveryTime.atZone(ZoneId.systemDefault()).toInstant()));
9    hideKeyboard(v);
10    tomtomMap.zoomToAllMarkers();

The first thing we do is get a reference to the text field with the delivery time and the Schedule Delivery button. We add a click listener on the button, which gets the text from the delivery time field and splits it. Ideally, we’d validate these values, but for the sake of brevity, we’ll assume that the input format is hour:minute.

We call the requestRoute function with our current location, the destination, the travel mode, which we hardcode to Truck, and the delivery time. The delivery time allows TomTom to compensate for typical traffic conditions based on the time of day.

2private void requestRoute(final LatLng departure, final LatLng destination, TravelMode byWhat, Date arriveAt) {
3    RouteQuery routeQuery = new RouteQueryBuilder(departure, destination)
4            .withRouteType(RouteType.FASTEST)
5            .withConsiderTraffic(true)
6            .withTravelMode(byWhat)
7            .withArriveAt(arriveAt)
8            .build();
10    routingApi.planRoute(routeQuery)
11            .subscribeOn(
12            .observeOn(AndroidSchedulers.mainThread())
13            .subscribe(new DisposableSingleObserver() {
14                @Override
15                public void onSuccess(RouteResponse routeResponse) {
16                    if (routeResponse.hasResults()) {
17                        FullRoute fullRoute = routeResponse.getRoutes().get(0);
18                        int currentTravelTime = fullRoute.getSummary().getTravelTimeInSeconds();
19                        LocalDateTime departureTime = arriveAt.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().minusSeconds(currentTravelTime);
20                        Toast.makeText(getApplicationContext(), "Depart at " + departureTime.format(timeFormatter), Toast.LENGTH_LONG).show();
21                        displayRouteOnMap(fullRoute.getCoordinates());
22                    }
23                }
25                @Override
26                public void onError(Throwable e) {
27                    Toast.makeText(getApplicationContext(), "Error finding the route.", Toast.LENGTH_LONG).show();
28                }
30                private void displayRouteOnMap(List coordinates) {
31                    RouteBuilder routeBuilder = new RouteBuilder(coordinates)
32                            .isActive(true);
33                    tomtomMap.clear();
34                    tomtomMap.addRoute(routeBuilder);
35                    tomtomMap.displayRoutesOverview();
36                }
37            });

The RouteAPI allows you to set different parameters. For our query, we’re looking for the fastest route, and we want consideration given to traffic at the time of day. Additional options available are the ability to select the most economical route, shortest route, and you can even submit fuel consumption information and receive an estimate for the amount of fuel required.

Once the route is generated, we display it on the Map, and then we calculate the required departure time and display it to the user as a pop-up within the app.

Learning More and Moving Beyond This Example

This application provides a basic introduction to the APIs for TomTom Search API, Routing API and Map Display API, as well as the Android SDK. If you would like to look at the source code in its entirety, you can download it from GitHub.

TomTom provides a more extensive example which you can learn more about here.

For more information about the APIs used in this example, including additional options and capabilities, you can review the documentation through the links below:

To read more tutorials on truck routing, check out these related articles:

Looking for powerful mapping and geolocation solutions?

TomTom's comprehensive APIs, years of engineering innovation, and decades of traffic data and trends provide everything you need to stand out from the competition. Read more about our fleet management & logistics products and contact us today for a consultation here.

Get the developer newsletter.
No marketing fuff. Tech content only.

* Required field. By submitting your contact details to TomTom, you agree that we can contact you about marketing offers, newsletters, or to invite you to webinars and events. We could further personalize the content that you receive via cookies. You can unsubscribe at any time by the link included in our emails. Review our privacy policy.