Skip to main content
GuidesAPI ReferenceExamples

Routing

Estimated reading time: 4 minutes

In this guide you will learn how to compute a route from a departure point to a destination point and display the route length in kilometers, and duration in hours:minutes as text on screen.

Setup

  1. Get your Magic Lane API key token: if you do not have a token, see the Getting Started guide
  2. Download the Maps & Navigation SDK for Android archive file
  3. Download the Routing project archive file or clone the project with Git
  4. See the Configure Android Example guide

Run the example

In Android Studio, from the File menu, select Sync Project with Gradle Files

An android device should be connected via USB cable.
Press SHIFT+F10 to compile, install and run the example on the android device.


How it works

How it works

You can open the MainActivity.kt file to see how the route is computed and the statistics of the computed route are displayed.

private val routingService = RoutingService(
onStarted = {
progressBar.visibility = View.VISIBLE
},
onCompleted = onCompleted@{ routes, errorCode, _ ->
progressBar.visibility = View.GONE
when (errorCode) {
GemError.NoError -> {
if (routes.size == 0) return@onCompleted
// Get the main route from the ones that were found.
displayRouteInfo(formatRouteName(routes[0]))
}
GemError.Cancel -> {
// The routing action was canceled.
}
else -> {
// There was a problem at computing the routing operation.
Toast.makeText(
this@MainActivity,
"Routing service error: ${GemError.getMessage(errorCode)}",
Toast.LENGTH_SHORT
).show()
}
}
}
)

A RoutingService() is instantiated, to compute a route, with an onStarted and an onCompleted listener, to receive notifications from the routing service when a route computation starts and when it is completed.

private fun calculateRoute() = SdkCall.execute {
val wayPoints = arrayListOf(
Landmark("Frankfurt am Main", 50.11428, 8.68133),
Landmark("Karlsruhe", 49.0069, 8.4037),
Landmark("Munich", 48.1351, 11.5820)
)
routingService.calculateRoute(wayPoints)
}

The starting, or departure point of the route is the first waypoint in a list of 2 or more Landmarks (3 in this case), each containing a name, latitude (in degrees) and longitude (in degrees). The destination point is the last waypoint in the list. The calculateRoute() function passes the list of waypoints to the routing service to calculate the route: routingService.calculateRoute(wayPoints).

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressBar = findViewById(R.id.progressBar)

SdkSettings.onMapDataReady = onMapDataReady@{ isReady ->
if (!isReady) return@onMapDataReady
// Defines an action that should be done after the world map is updated.
calculateRoute()
}
SdkSettings.onApiTokenRejected = {
Toast.makeText(this, "TOKEN REJECTED", Toast.LENGTH_LONG).show()
}
if (!GemSdk.initSdkWithDefaults(this)) {
// The SDK initialization was not completed.
finish()
}
if (!Util.isInternetConnected(this)) {
Toast.makeText(this, "You must be connected to internet!",
Toast.LENGTH_LONG).show()
}
}

The MainActivity overrides the onCreate() function which checks that internet access is available, and then, when the map is instantiated and ready (although the map is not rendered in this example), starts the route calculation: calculateRoute().

private fun displayRouteInfo(routeName: String) {
findViewById<TextView>(R.id.text).text = routeName
}

The routingService listener above receives the onCompleted notification when the route computation is complete, and if there is at least one resulting route, then it takes the first route in the list (at index 0) and calls displayRouteInfo(formatRouteName(routes[0])) to print the route length in kilometers and duration in hours:minutes as text on screen.

The route statistics text printed by displayRouteInfo() is formatted by formatRouteName() :

private fun formatRouteName(route: Route): String = SdkCall.execute {
val timeDistance = route.timeDistance ?: return@execute ""
val distInMeters = timeDistance.totalDistance
val timeInSeconds = timeDistance.totalTime
val distTextPair = GemUtil.getDistText(
distInMeters,
SdkSettings.unitSystem,
bHighResolution = true
)
val timeTextPair = GemUtil.getTimeText(timeInSeconds)
var wayPointsText = ""
route.waypoints?.let { wayPoints ->
for (point in wayPoints) {
wayPointsText += (point.name + "\n")
}
}
return@execute String.format(
"$wayPointsText \n\n ${distTextPair.first} ${distTextPair.second} \n " +
"${timeTextPair.first} ${timeTextPair.second}"
)
} ?: ""

Android Examples

Maps SDK for Android Examples can be downloaded or cloned with Git