This article shows how to use the TomTom Maps SDK for Android to create an application that
calculates the time to leave previous to reaching the destination point at the desired time.
Getting Started
A user can plan their route to reach the destination by using the following:
Departure and destination locations.
Travel mode.
The time they want to reach the destination.
Optionally preparation time before the departure.
Next:
The route is calculated and displayed on a map.
The time to leave timer starts to count down.
The route is recalculated each minute to check for any traffic delays.
In case of any changes in traffic, the countdown timer gets updated and the user is notified.
This article does not cover the whole of the application's code description, only the code sections
where the TomTom SDK is used.
You can find and clone the working application on
our GitHub. Have
fun with modifying it and testing our APIs! If you want to follow a step-by-step application
creation from scratch, check out the “Search Along the Route” tutorial.
The following sections describe the usage of:
The TomTom LocationSource API to get the user's current location
The TomTom Search SDK module to search for addresses and geocode map positions
The TomTom Map SDK module to display a map
The TomTom Routing SDK module to plan routes
Prerequisites:
Clone a GitHub repository, with the source code of the TimeToLeave application:
To get the users device location, a LocationSource class is used. This class uses
LocationUpdateListener interface to notify about new location updates.
The application needs to have proper permissions granted which is handled
by onRequestPermissionsResult callback, so that location callbacks can be retrieved successfully.
A PermissionChecker class is used to check whether the application has already assigned proper
permissions. If not, then a requestPermissions function is called so that the user sees a
permission request dialog. If location permissions have been granted inside
an onRequestPermissionsResult function, a locationSource.activate() method is invoked. As a
result, the application receives a GPS location in an onLocationChanged callback function.
Then, a searchAddress function handles points of interest (POI) & address search. It takes two
parameters:
A search word which is used inside a query.
An AutoCompleteTextView object which is used to match whether an afterTextChanged event has
been called from the departure text field instead of the destination field.
Inside the searchAddress function, a searchApi.search(...) method is called.
It takes a FuzzySearchQuery object as a parameter where you can provide necessary information
like search results language, category, position etc.
FuzzySearchQueryBuilder is used to build the FuzzySearchQuery object.
The following list of options can set the search query:
withLanguage(Locale.getDefault().toLanguageTag()) - to return the results in default
language on the mobile device.
withTypeAhead(true)) - to treat the searchWord query as a partial input and search service
enters a predictive mode.
withMinFuzzyLevel(2)) - to set the fuzziness level to use normal n-gram spell checking. Feel
free to experiment with other fuzziness levels.
The search method from the searchApi object, returns a FuzzySearchResponse observable
object.
When search operation is finished, it emits either a successful value or an error.
If a successful value is emitted, a method named onSuccess is executed in the
subscribing DisposableSingleObserver, otherwise an onError method is executed.
The same searchAddress function is used in the destination text field control.
If there are any results in the FuzzySearchResponse object and the current location is
known, then it is added to the departure autocomplete list of suggestions as a first option.
Then this list is filled with addresses from the FuzzySearchResponse object.
When the departure position is set, the user can choose destination position, arrival time,
preparation time and a travel mode. All these parameters are gathered and passed to
a CountDownActivity.prepareIntent method.
1Intent intent =CountdownActivity.prepareIntent(
2MainActivity.this,
3 latLngDeparture,
4 latLngDestination,
5 travelModeSelected,
6 arrivalTimeInMillis,
7 preparationTimeSelected);
8startActivity(intent);
1val intent = CountdownActivity.prepareIntent(
2this@MainActivity,
3 latLngDeparture,
4 latLngDestination,
5 travelModeSelected,
6 arrivalTimeInMillis,
7 preparationTimeSelected)
8startActivity(intent)
TomTom Map display module
A CountDown activity uses map and routing modules from the TomTom Maps SDK. It implements
an OnMapReadyCallback interface, so that an onMapReady method is called after the TomTom map is
ready to be used.
After the startActivity method is called inside a CountDownActivity.onCreate(...) method, TomTom
services and all other settings gathered from previous activity are initialized.
When the map is ready to be used, TomTom SDK automatically invokes an onMapReady callback method
where:
The tomtomMap private field is initialized.
An 'in progress' dialog is displayed.
A requestRoute method is called.
TomTom Routing module
The CountDown activity uses TomTom Routing APIs to perform routing requests and operations like
drawing a route on the map or displaying start and end route icons.
First, a private RoutingApi class member is declared and initialized inside
an initTomTomServices function which is shown in several previous paragraphs.
The requestRoute method takes four parameters:
LatLng departure position,
LatLng destination position,
TravelMode which describes which type of transport user choosed,
The RouteDescriptor and RouteCalculationDescriptor are used to construct
the RouteSpecification object:
routeType - to allow the users to select one type of route from: fastest, shortest, thrilling
or eco.
considerTraffic - when enabled, current traffic information is used during the route planning, when disabled - only historical traffic data.
travelMode – you can choose one of the following: car, pedestrian, bicycle, truck, other params are listed here.
arriveAt - a date and time of arrival at the destination point. It’s an important method
inside the application because it changes a departure date which later is used to calculate time
left before the departure.
When the RouteSpecification object is created, it is passed as a parameter to a planRoute
function from the routingApi object. This function takes as an argument a RouteCallback
object. In case of an error, an onError method is called, inside this method the current
activity is finished. As a result, the application returns to the previous screen.
The most important task in previous code example is to get a current travel time and compare it
to the previous one.
If travel times are the same, a Snackbar notification is shown to the user informing him, that
there are no changes in the route time since the last check.
Otherwise a travel time difference is calculated and stored in a travelDifference variable.
Then, a snackbar notification is shown to the user with the calculated travel time difference.
Next, the current travel time is stored in a previousTravelTime variable.
The setupCountDownTimer function takes the departure date as a parameter. It checks if there is
already a countdown timer service already running in the background, and if there is, it cancels
it. Next, a current date is stored in a currentDate variable and the preparation time taken
from the first activity is stored in a preparationTimeMillis variable. A time difference
between the departure time and the current time is stored in a timeToLeave variable. It is
later passed to a CountDownTimer constructor.
The CountDownTimer class implements two callbacks:
The first callback is called onTick(long millisUntilFinished).
It updates time info and checks whether the application is in a preparation mode.
If this is the case, the color of the timer text views changes, and a preparation dialog is
displayed to the user.
onFinish() is called by the timer when counting down is completed.
In this function, requestRouteRunnable callback is removed from timerHandler’s queue by
calling removeCallbacks method.
The color of a timer text views is updated again, and final alert dialog window is displayed
to the user with nicely designed message that there is a time to leave!
Happy coding!
Summary
This tutorial describes the TomTom SDK and APIs used to build a Time To Leave application. Source
code can be downloaded
from Github.