Skip to main content

Get started with routing

|

Here's a quick overview of what you can do with routing:

  • Calculate routes from a start point to a destination.
  • Include intermediary waypoints for multi-stop routes.
  • Compute range routes to determine areas reachable within a specific range.
  • Plan routes over predefined tracks.
  • Customize routes with preferences like route types, restrictions, and more.
  • Retrieve maneuvers and turn-by-turn instructions.
  • Access detailed route profiles for further analysis.

Calculate routes

You can calculate a route with the code below. This route is navigable, which means that later it is possible to do a navigation/ simulation on it.

// Define the departure landmark
val departureLandmark = Landmark().apply {
coordinates = Coordinates(48.85682, 2.34375)
}

// Define the destination landmark
val destinationLandmark = Landmark().apply {
coordinates = Coordinates(50.84644, 4.34587)
}

// Define the route preferences (all default)
val routePreferences = RoutePreferences()

// Create waypoints list
val waypoints = arrayListOf(departureLandmark, destinationLandmark)

// Create routing service
val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
if (errorCode == GemError.Success) {
Log.d("Routing", "Number of routes: ${routes.size}")
} else if (errorCode == GemError.Cancel) {
Log.d("Routing", "Route computation canceled")
} else {
Log.e("Routing", "Error: $errorCode")
}
}
)

// Calculate the route
val result = routingService.calculateRoute(waypoints)
info

The RoutingService.calculateRoute method returns an Int status code. When the computation fails to initiate, the onCompleted callback will be triggered with the appropriate error code. You can call RoutingService.cancelRoute() to cancel an ongoing route calculation.

The errorCode provided by the callback function can have the following values:

ValueSignificance
GemError.Successsuccessfully completed
GemError.Cancelcancelled by the user
GemError.WaypointAccesscouldn't be found with the current preferences
GemError.ConnectionRequiredif allowOnlineCalculation = false in the routing preferences and the calculation can't be done on the client side due to missing data
GemError.Expiredcalculation can't be done on client side due to missing necessary data and the client world map data version is no longer supported by the online routing service
GemError.RouteTooLongrouting was executed on the online service and the operation took too much time to complete (usually more than 1 min, depending on the server overload state)
GemError.Invalidatedthe offline map data changed ( offline map downloaded, erased, updated ) during the calculation
GemError.NoMemoryrouting engine couldn't allocate the necessary memory for the calculation

The previous example shows how to define your start and end points, set route preferences, and handle the callback for results. If needed, you can cancel the ongoing computation:

routingService.cancelRoute()

When the route is canceled, the callback will return errorCode = GemError.Cancel.

Get ETA and traffic information

Once the route is computed, you can retrieve additional details like the estimated time of arrival (ETA) and traffic information. Here's how you can access these:

val td = route.getTimeDistance(activePart = false)

val totalDistance = td?.totalDistance
// same with:
//val totalDistance = (td?.unrestrictedDistance ?: 0) + (td?.restrictedDistance ?: 0)

val totalDuration = td?.totalTime
// same with:
//val totalDuration = (td?.unrestrictedTime ?: 0) + (td?.restrictedTime ?: 0)

// by default activePart = true
val remainTd = route.getTimeDistance(activePart = true)

val totalRemainDistance = remainTd?.totalDistance
val totalRemainDuration = remainTd?.totalTime

By using the method Route.getTimeDistance we can get the time and distance for a route. If the activePart parameter is false, it means the distance is computed for the entire route initially computed, otherwise it is computed only for the active part (the part still remaining to be navigated). The default value for this parameter is true.

In the example unrestricted means the part of the route that is on public property and restricted the part of the route that is on private property. Time is measured in seconds and distance in meters.

If you want to gather traffic details, you can do so like this:

val trafficEvents = route.trafficEvents

trafficEvents?.forEach { event ->
val transportMode = event.affectedTransportMode
val description = event.description
val eventClass = event.eventClass
val eventSeverity = event.eventSeverity
val from = event.from
val to = event.to
val isRoadBlock = event.isRoadblock()
}

Check the Traffic Events guide for more details.

Display routes on map

After calculating the routes, they are not automatically displayed on the map. To visualize and center the map on the route, refer to the display routes on maps related documentation. The Maps SDK for Android offers extensive customization options, allowing for flexible preferences to tailor the display to your needs.

Get the Terrain Profile

When computing the route we can choose to also build the TerrainProfile for the route.

In order to do that RoutePreferences must specify we want to also generate the terrain profile:

val routePreferences = RoutePreferences().apply {
buildTerrainProfile = true
}
danger

Setting the buildTerrainProfile property to true in the preferences used within calculateRoute is mandatory for getting route terrain profile data.

Later, use the profile for elevation data or other terrain-related details:

val terrainProfile = route.terrainProfile

terrainProfile?.let { profile ->
val minElevation = profile.minElevation
val maxElevation = profile.maxElevation
val minElevDist = profile.minElevationDistance
val maxElevDist = profile.maxElevationDistance
val totalUp = profile.totalUp
val totalDown = profile.totalDown

// elevation at 100m from the route start
val elevation = profile.getElevation(100)

profile.roadTypeSections?.forEach { section ->
val roadType = section.type
val startDistance = section.startDistanceM
}

profile.surfaceSections?.forEach { section ->
val surfaceType = section.type
val startDistance = section.startDistanceM
}

profile.climbSections?.forEach { section ->
val grade = section.grade
val slope = section.slope
val startDistanceM = section.startDistanceM
val endDistanceM = section.endDistanceM
}

val categs = arrayListOf(-16f, -10f, -7f, -4f, -1f, 1f, 4f, 7f, 10f, 16f)

val steepSections = profile.getSteepSections(categs)
steepSections?.forEach { section ->
val categ = section.category
val startDistanceM = section.startDistanceM
}
}

ERoadType possible values are: Motorways, StateRoad, Road, Street, Cycleway, Path, SingleTrack.

ESurfaceType possible values are: Asphalt, Paved, Unpaved, Unknown.

Route profile chart
Route profile sections

Get the route segments and instructions

Once a route has been successfully computed, you can retrieve a detailed list of its segments. Each segment represents the portion of the route between two consecutive waypoints and includes its own set of route instructions.

For instance, if a route is computed with five waypoints, it will consist of four segments, each with distinct instructions.

In the case of public transit routes, segments can represent either pedestrian paths or public transit sections.

Here's an example of how to access and use this information, focusing on some key RouteInstruction properties:

FieldTypeExplanation
traveledTimeDistanceTimeDistance?Time and distance from the beginning of the route.
remainingTravelTimeDistanceTimeDistance?Time and distance to the end of the route.
coordinatesCoordinates?The coordinates indicating the location of the instruction.
remainingTravelTimeDistanceToNextWaypointTimeDistance?Time and distance until the next waypoint.
timeDistanceToNextTurnTimeDistance?Time and distance until the next instruction.
turnDetailsTurnDetails?Get full details for the turn.
turnInstructionString?Get textual description for the turn.
roadInfoArrayList<RoadInfo>?Get road information.
hasRoadInfoBooleanCheck if road information is available.
followRoadInstructionString?Get textual description for the follow road information.
hasFollowRoadInfoBooleanCheck if follow road information is available.
countryCodeISOString?Get ISO 3166-1 alpha-3 country code for the navigation instruction.
hasSignpostInfoBooleanCheck if signpost information is available.
signpostInstructionString?Get textual description for the signpost information.
signpostDetailsSignpostDetails?Get extended signpost details.
hasTurnInfoBooleanCheck if turn information is available.
turnImageImage?Get turn image. The user is responsible to check if the image is valid.
realisticNextTurnImageAbstractGeometryImage?Get customizable image for the realistic turn information. The user is responsible to check if the image is valid.
roadInfoImageRoadInfoImage?Get customizable road image. The user is responsible to check if the image is valid.
isFerryBooleanReturns true if the route instruction is a ferry.
isTollRoadBooleanReturns true if the route instruction is a toll road.
isCommonBooleanCheck if this instruction is of common type.
List containing route instructions

Data from the instruction list above is obtained via the following properties of RouteInstruction:

  • turnInstruction : Bear left onto A 5.
  • followRoadInstruction : Follow A 5 for 132m.
  • traveledTimeDistance?.totalDistance : 6.2km. (after formatting to km)
  • turnDetails?.abstractGeometryImage?.asBitmap() : Instruction image or null when image is invalid.