Skip to main content

Advanced features

|

Compute route ranges

In order to compute a route range we need to:

  • Specify in the RoutePreferences the most important route preferences (others can also be used):
    • routeRanges list containing a list of range values, one for each route we compute. Measurement units are corresponding to the specified routeType (see the table below)
    • [optional] transportMode (by default ERouteTransportMode.Car)
    • [optional] routeType (can be ERouteType.Fastest, ERouteType.Economic, ERouteType.Shortest - by default is fastest)
    • [optional] routeRangesQuality ( a value in the interval [0, 100], default 100) representing the quality of the generated polygons.
  • The list of landmarks will contain only one landmark, the starting point for the route range computation.
PreferenceMeasurement unit
fastestseconds
shortestmeters
economicWh
danger

Routes computed using route ranges are not navigable.

danger

The ERouteType.Scenic route type is not supported for route ranges.

Route can be computed with a code like the following. It is a range route computation because it only has a simple Landmark and routeRanges contains values (in this case 2 routes will be computed).

SdkCall.execute {
// Define the departure.
val startLandmark = Landmark("Start", 48.85682, 2.34375)

// Define the route preferences.
// Compute 2 ranges, 30 min and 60 min
val routePreferences = RoutePreferences().apply {
routeType = ERouteType.Fastest
setRouteRanges(arrayListOf(1800, 3600), 100) // quality = 100
}

val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
// Route range computed successfully
// Display routes on map using the additional fill color setting
mapView?.presentRoutes(routes)
}
GemError.Cancel -> {
// Route computation canceled
}
else -> {
// Error occurred
showDialog("Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

routingService.calculateRoute(arrayListOf(startLandmark))
}
info

The computed routes can be displayed on the map, just like any regular route, with the only difference that the additional settings for polygon fill color can be configured in the route render settings.

Compute path based routes

A Path is a structure containing a list of coordinates (a track). It can be created based on:

  • custom coordinates specified by the user
  • coordinates recorded in a GPX file
  • coordinates obtained by doing a finger draw on the map

A Path backed landmark is a special kind of Landmark that has a Path inside it.

Sometimes we want to compute routes based on a list of one or more Path backed landmark(s) and optionally some regular Landmark(s). In this case the result will only contain one route. The path provided as waypoint track is used as a hint for the routing algorithm.

You can see an example below (the highlighted area represents the code necessary to create the list with one element of type landmark built based on a path):

SdkCall.execute {
val coords = arrayListOf(
Coordinates(40.786, -74.202),
Coordinates(40.690, -74.209),
Coordinates(40.695, -73.814),
Coordinates(40.782, -73.710)
)

val gemPath = Path.produceWithCoords(coords)

// A list containing only one Path backed Landmark
val landmarkList = arrayListOf(gemPath?.toLandmark())

// Define the route preferences.
val routePreferences = RoutePreferences()

val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
// Route computed successfully
showSnackbar("Number of routes: ${routes.size}")
}
GemError.Cancel -> {
// Route computation canceled
}
else -> {
// Error occurred
showDialog("Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

routingService.calculateRoute(landmarkList.filterNotNull() as ArrayList<Landmark>)
}
Tip

The Path object associated to a path based landmark can be modified using the trackData property available on the Landmark object. See the Landmarks guide for more details about this.

danger

When computing a route based on a path backed landmark and non-path backed landmarks, it is mandatory to set the accurateTrackMatch field from RoutePreferences to true. Otherwise, the routing computation will fail with a GemError.Unsupported error.

The isTrackResume field from RoutePreferences can also be set to configure the behaviour of the routing engine when one track based landmark is used as a waypoint together with other landmarks. If this field is set to true, the routing engine will try to match the entire track of the path based landmark. Otherwise, if set to false, only the end point of the track will be used as waypoints.

Computing a route based on a GPX file

You can compute a route based on a GPX file by using the path based landmark described in the previous section. The only difference is how we compute the gemPath.

SdkCall.execute {
// Load GPX file from assets
val gpxAssetsFilename = "gpx/recorded_route.gpx"
val inputStream = applicationContext.resources.assets.open(gpxAssetsFilename)

// Produce a Path based on the GPX data
val gemPath = Path.produceWithGpx(inputStream)

gemPath?.let { path ->
// LandmarkList will contain only one path based landmark.
val landmarkList = arrayListOf(path.toLandmark())

// Define the route preferences.
val routePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Bicycle
}

val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
// Handle successful route calculation
mapView?.presentRoutes(routes)
}
GemError.Cancel -> {
// Route computation canceled
}
else -> {
// Error occurred
showDialog("Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

routingService.calculateRoute(landmarkList)
} ?: run {
showDialog("GPX file could not be loaded")
}
}

Finger drawn path

When necessary, it is possible to record a path based on drawing with the finger on the map.

It is also possible to record multiple paths. In this situation a straight line is added between any 2 consecutive finger drawn paths.

When you want to enter this recording mode:

SdkCall.execute {
mapView?.enableDrawMarkersMode()
}

When you want to exit this mode, you can get the generated List<Landmark> with the following:

SdkCall.execute {
val landmarks = mapView?.disableDrawMarkersMode()

landmarks?.let { landmarkList ->
val routePreferences = RoutePreferences().apply {
accurateTrackMatch = false
ignoreRestrictionsOverTrack = true
}

val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
// Handle successful route calculation
mapView?.presentRoutes(routes)
}
GemError.Cancel -> {
// Route computation canceled
}
else -> {
// Error occurred
showDialog("Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

routingService.calculateRoute(landmarkList)
}
}

The resulted List<Landmark> will only contain one element, a path based Landmark.

Compute public transit routes

In order to compute a public transit route we need to set the transportMode field in the RoutePreferences like this:

// Define the route preferences with public transport mode.
val routePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Public
}
danger

Public transit routes are not navigable.

The full source code to compute a public transit route and handle it could look like this:

SdkCall.execute {
// Define the departure.
val departureLandmark = Landmark("Departure", 45.6646, 25.5872)

// Define the destination.
val destinationLandmark = Landmark("Destination", 45.6578, 25.6233)

// Define the route preferences with public transport mode.
val routePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Public
}

val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
when (errorCode) {
GemError.NoError -> {
if (routes.isNotEmpty()) {
// Get the routes collection from map preferences.
val routesMap = mapView?.preferences?.routes

// Display the routes on map.
routes.forEachIndexed { index, route ->
routesMap?.add(route, index == 0, if (index == 0) "Route" else null)
}

// Convert normal route to PTRoute
val ptRoute = routes.first().toPTRoute()

// Convert each segment to PTRouteSegment
val ptSegments = ptRoute?.segments?.map { segment ->
segment.toPTRouteSegment()
}

ptSegments?.forEach { segment ->
segment?.let { ptSegment ->
val transitType = ptSegment.transitType

if (ptSegment.isCommon()) { // PT segment
val ptInstructions = ptSegment.instructions?.map { instruction ->
instruction.toPTRouteInstruction()
}
ptInstructions?.forEach { ptInstr ->
ptInstr?.let { instruction ->
// handle public transit instruction
val stationName = instruction.name
val departure = instruction.departureTime
val arrival = instruction.arrivalTime
// ...
}
}
} else { // walk segment
val instructions = ptSegment.instructions
instructions?.forEach { walkInstr ->
// handle walk instruction
}
}
}
}
}
}
GemError.Cancel -> {
// Route computation canceled
}
else -> {
// Error occurred
showDialog("Error: ${GemError.getMessage(errorCode)}")
}
}
}
)

routingService.calculateRoute(arrayListOf(departureLandmark, destinationLandmark))
}

Once routes are computed, if the computation was for public transport route, you can convert a resulted route to a public transit route via toPTRoute(). After that you have full access to the methods specific to this kind of route.

A public transit route is a sequence of one or more segments. Each segment is either a walking segment, either a public transit segment. You can determine the segment type based on the ETransitType.

ETransitType can have the following values: Walk, Bus, Underground, Railway, Tram, WaterTransport, Other, SharedBike, SharedScooter, SharedCar, Unknown.

Tip

Other settings related to public transit (such as departure/arrival time) can be specified within the RoutePreferences object passed to the calculateRoute method:

val customRoutePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Public
// The arrival time is set to one hour from now.
algorithmType = EPTAlgorithmType.Arrival
timestamp = Time(System.currentTimeMillis() + 3600000) // 1 hour from now
// Sort the routes by the best time.
sortingStrategy = EPTSortingStrategy.BestTime
// Accessibility preferences
useBikes = false
useWheelchair = false
}

Export a Route to file

The exportToFile method allows you to export a route from RouteBookmarks into a file on disk. This makes it possible to store the route for later use or share it with other systems.

The file will be saved at the exact location provided in the filePath parameter, so always ensure the directory exists and is writable.

SdkCall.execute {
val routeBookmarks = RouteBookmarks.produce("MyRoutes")
routeBookmarks?.let { bookmarks ->
//index of the route in this bookmark collection and filepath
val error = bookmarks.exportToFile(index, filePath)
when (error) {
GemError.NoError -> {
// Route exported successfully
}
GemError.NotFound -> {
// The given route index does not exist
}
GemError.Io -> {
// File cannot be created or written to
}
else -> {
// Other error occurred
}
}
}
}
Tip

When exporting a route, make sure to handle possible errors:

  • GemError.NotFound - This occurs if the given route index does not exist.
  • GemError.Io - This occurs if the file cannot be created or written to.

Export a Route as String

The exportAs method allows you to export a route into a textual representation. The returned value is a DataBuffer containing the full route data in the requested format. This makes it easy to store the route as a file or share it with other applications that support formats like GPX, KML, NMEA, or GeoJSON.

SdkCall.execute {
val route = routes.first()
val dataBuffer = route.exportAs(EPathFileFormat.Gpx)
dataBuffer?.let { buffer ->
// You now have the full GPX as a DataBuffer
// Convert to string if needed
val gpxString = String(buffer.data)
}
}