Skip to main content

Handling RoutePreferences

|

Before computing a route, we need to specify some route options using the RoutePreferences class.

Route Preferences structure

Core Routing Properties

PropertyTypeDefault ValueExplanation
Basic Route Configuration
routeTypeERouteTypeERouteType.FastestPreferred route type (Fastest, Shortest, Economic, Scenic).
transportModeERouteTransportModeERouteTransportMode.CarTransport mode (Car, Lorry, Pedestrian, Bicycle, Public, SharedVehicles).
resultDetailsERouteResultDetailsERouteResultDetails.FullLevel of details in the route result (Full, TimeDistance, Path).
alternativesSchemaERouteAlternativesSchemaERouteAlternativesSchema.DefaultSchema for alternative routes (Default, Never, Always).
pathAlgorithmERoutePathAlgorithmERoutePathAlgorithm.MagicEarthAlgorithm used for path calculation (MagicEarth, ExternalCh).
Route Constraints
maximumDistanceConstraintBooleantrueEnables maximum distance constraints based on transport and result details.
alternativeRoutesBalancedSortingBooleantrueBalances sorting of alternative routes.
accurateTrackMatchBooleantrueEnables accurate track matching for routes.
ignoreRestrictionsOverTrackBooleanfalseIgnores map restrictions in route-over-track mode.
Timing and Schedule
timestampTime?null (automatic)Custom timestamp for PT routes (departure/arrival time).
isAutomaticTimestamp()BooleantrueReturns if timestamp is set to automatic mode.
setIsAutomaticTimestamp()Function-Sets timestamp to automatic mode for PT routes.
Geofencing
avoidGeofenceAreasArrayList<String>empty listList of geofence area IDs to avoid during routing.
stickInsideGeofenceAreasArrayList<String>empty listList of geofence area IDs to stay inside during routing.

Route Avoidance Options

PropertyTypeDefault ValueExplanation
avoidMotorwaysBooleanfalseAvoids motorways in the route.
avoidTollRoadsBooleanfalseAvoids toll roads in the route.
avoidFerriesBooleanfalseAvoids ferries in the route.
avoidUnpavedRoadsBooleanfalseAvoids unpaved roads in the route.
avoidCarpoolLanesBooleanfalseAvoids carpool lanes.
avoidTurnAroundInstructionBooleanfalseAvoids turn-around instructions during navigation.
avoidTrafficETrafficAvoidanceETrafficAvoidance.NoneTraffic avoidance strategy (None, All, Roadblocks).
avoidBikingHillFactorFloat0.5Factor to avoid biking hills (0.0-1.0).

Vehicle Profile Configuration

PropertyTypeDefault ValueExplanation
Car Profile
carProfileCarProfile?nullCar-specific routing preferences (fuel type, mass, max speed).
Truck Profile
truckProfileTruckProfile?nullTruck-specific routing preferences (dimensions, weight, axle load).
Electric Vehicle Profile
evProfileEVProfile?nullElectric vehicle routing preferences (battery, charging, efficiency).
Bike Profiles
bikeProfileEBikeProfileEBikeProfile.RoadSelected bike profile (Road, Cross, City, Mountain).
eBikeProfileElectricBikeProfile?nullElectric bike profile configuration.
defaultEBikeProfileElectricBikeProfile?nullDefault electric bike profile.
setBikeProfile()Function-Sets bike profile with optional electric bike configuration.
Pedestrian Profile
pedestrianProfileEPedestrianProfileEPedestrianProfile.WalkPedestrian profile (Walk, Hike).

Public Transport Options

PropertyTypeDefault ValueExplanation
algorithmTypeEPTAlgorithmTypeEPTAlgorithmType.DepartureAlgorithm type for PT routing (Departure, Arrival).
sortingStrategyEPTSortingStrategyEPTSortingStrategy.BestTimeStrategy for sorting PT routes (BestTime, LeastWalk, LeastTransfers).
minimumTransferTimeInMinutesInt1Minimum transfer time in minutes.
maximumTransferTimeInMinutesInt300Maximum transfer time in minutes.
maximumWalkDistanceInt5000Maximum walking distance in meters.
routeTypePreferencesInt0 (no preference)PT route type preferences (bit flags for Bus, Underground, etc.).
useBikesBooleanfalseEnables use of bikes in PT routes.
useWheelchairBooleanfalseEnables wheelchair-friendly PT routes.
routeGroupIdsEarlierLaterArrayList<Int>?nullIDs for earlier/later route groups.

Route Enhancement Features

PropertyTypeDefault ValueExplanation
Terrain Profile
buildTerrainProfileBooleanfalseEnables building of terrain profile.
setBuildTerrainProfile()Function-Sets terrain profile build with optional minimum elevation variation.
Route Connections
setBuildConnections()Function-Enables building of route connections with max length.
getBuildConnections()Function-Returns if route connections building is enabled.
getBuildConnectionsMaxLength()Function-Returns maximum connection length in meters.
Route Ranges (Isochrones)
routeRangesArrayList<Int>?nullRoute ranges for isochrone calculation.
routeRangesQualityInt100Quality level for route ranges (0-100).
setRouteRanges()Function-Sets route ranges with quality level.
Departure Heading
departureHeadingDouble-1 (no heading)Departure heading in degrees (0-360, -1 = no heading).
setDepartureHeading()Function-Sets departure heading with accuracy.

Emergency Vehicle Options

PropertyTypeDefault ValueExplanation
emergencyVehicleModeBooleanfalseEnables emergency vehicle mode (read-only).
setEmergencyVehicleMode()Function-Sets emergency vehicle mode with extra freedom levels.

Read-Only Properties

PropertyTypeDefault ValueExplanation
routeResultTypeERouteResultTypeERouteResultType.PathType of route result (Path, Range) - read-only.
info

For timestamp usage with Public Transport routes, the SDK supports both automatic and manual timestamp setting. When isAutomaticTimestamp() returns true, the departure timestamp is set to the local time of the departing waypoint.

// Set automatic timestamp (default behavior)
routePreferences.setIsAutomaticTimestamp()

// Set custom timestamp
val customTime = Time().apply {
// Set your desired departure/arrival time
setLocalTime() // or set specific time values
}
routePreferences.timestamp = customTime

// Check if automatic timestamp is enabled
val isAutomatic = routePreferences.isAutomaticTimestamp()

Basic Usage Example

A short example of how to configure basic route preferences for the fastest car route with terrain profile:

val routePreferences = RoutePreferences().apply {
// Basic route configuration
transportMode = ERouteTransportMode.Car
routeType = ERouteType.Fastest
resultDetails = ERouteResultDetails.Full

// Enable terrain profile calculation
setBuildTerrainProfile(true, 5.0f) // 5m minimum elevation variation

// Avoid certain road types
avoidMotorways = false
avoidTollRoads = true
avoidFerries = false

// Set traffic avoidance
avoidTraffic = ETrafficAvoidance.All
}

Profiles structure

Car Profile

The CarProfile class is responsible for defining car specific routing preferences. The available options are presented in the following table:

MemberTypeDefaultDescription
fuelTypeEFuelTypeEFuelType.PetrolEngine fuel type
massInt0 - not considered in routing.Vehicle mass in kg.
maxSpeedDouble0.0 - not considered in routing.Vehicle max speed in m/s.

EFuelType can have the following values: Petrol, Diesel, LPG (liquid petroleum gas), Electric.

By default, all fields except fuelType have default value 0, meaning they are not considered in the routing. fuelType by default is EFuelType.Petrol.

val carProfile = CarProfile(
fuelType = EFuelType.Diesel,
mass = 1500, // kg
maxSpeed = 50.0 // m/s
)

Truck Profile

The TruckProfile class is responsible for defining truck specific routing preferences. The available options are presented in the following table:

MemberTypeDefaultDescription
axleLoadInt0 - not considered in routingTruck axle load in kg.
heightInt0 - not considered in routingTruck height in cm.
lengthInt0 - not considered in routingTruck length in cm.
massInt0 - not considered in routingVehicle mass in kg.
maxSpeedDouble0.0 - not considered in routingVehicle max speed in m/s.
widthInt0 - not considered in routingTruck width in cm.
val truckProfile = TruckProfile(
massKg = 3000,
heightCm = 350,
lengthCm = 1200,
widthCm = 250,
axleLoadKg = 11000,
maxSpeedMs = 25.0
)

Electric Vehicle Profile

The EVProfile class is responsible for defining electric vehicle specific routing preferences. The available options are presented in the following table:

MemberTypeDefaultDescription
nameString?nullCar model name.
towbarPossibleInt0Maximum weight available on vehicle towbar.
portsInt0Supported charging ports (combination of EEVChargingConnector).
departureSocFloat0.0Departure battery state of charge (0-1).
destinationSocFloat0.0Destination min battery state of charge (0-1).
chargerDestSocFloat0.0Charger destination min battery state of charge (0-1).
chargerDepSocFloat0.0Charger departure max battery state of charge (0-1).
chargerOverheadMinsInt0Charger time overhead in minutes.
batteryHealthFloat0.0Battery health (0-1, where 1 is brand new).
batteryCapacityInt0Battery capacity in watt hours.
vehicleRangeInt0Vehicle range in meters.
efficiencyInt0Consumption in Wh/km.
fastChargeInt0How many km charged in one hour (10-80 interval).

Electric Bike Profile

The ElectricBikeProfile class is responsible for defining electric bike specific routing preferences. The available options are presented in the following table:

MemberTypeDefaultDescription
typeEEBikeTypeEEBikeType.NoneE-bike type (None, Pedelec, PowerOnDemand).
bikeMassFloat0.0 - default value is usedBike mass in kg.
bikerMassFloat0.0 - default value is usedBiker mass in kg.
auxConsumptionDayFloat0.0 - default value is usedBike auxiliary power consumption during day in Watts.
auxConsumptionNightFloat0.0 - default value is usedBike auxiliary power consumption during night in Watts.
refSpeedFloat0.0 - default value is usedReference speed in m/s.
ignoreLegalRestrictionsBooleanfalseIgnore country-based legal restrictions related to e-bikes.
val electricBikeProfile = ElectricBikeProfile(
bikeType = EEBikeType.Pedelec,
bikeMassKg = 25.0f,
bikerMassKg = 70.0f,
auxConsDayW = 10.0f,
auxConsNightW = 15.0f
).apply {
ignoreLegalRestrictions = false
}

// Set bike profile with electric bike configuration
routePreferences.setBikeProfile(EBikeProfile.City, electricBikeProfile)

Computing truck routes

To compute routes for trucks we can write code like the following by initializing the truckProfile field of RoutePreferences:

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

// Define the destination landmark
val destinationLandmark = Landmark().apply {
coordinates = Coordinates(51.4739, -0.0302)
}

// Create truck profile
val truckProfile = TruckProfile(
massKg = 3000, // kg
heightCm = 180, // cm
lengthCm = 500, // cm
widthCm = 200, // cm
axleLoadKg = 1500, // kg
maxSpeedMs = 16.67 // m/s (60 km/h)
)

// Define the route preferences with truck profile and lorry transport mode
val routePreferences = RoutePreferences().apply {
this.truckProfile = truckProfile
transportMode = ERouteTransportMode.Lorry // <- This field is crucial
}

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

// Create routing service and calculate route
val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
if (errorCode == GemError.Success) {
// Handle successful route calculation
println("Number of routes: ${routes.size}")
} else {
// Handle error
println("Error calculating route: $errorCode - $hint")
}
}
)

val result = routingService.calculateRoute(waypoints)

Computing caravan routes

Certain vehicles, such as caravans or trailers, may be restricted on some roads due to their size or weight, yet still permitted on roads where trucks are prohibited.

To calculate routes for caravans or trailers, we can use the truckProfile field of RoutePreferences with the appropriate dimensions and weight.

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

// Define the destination landmark
val destinationLandmark = Landmark().apply {
coordinates = Coordinates(51.4739, -0.0302)
}

// Create caravan profile using TruckProfile
val caravanProfile = TruckProfile(
heightCm = 180, // cm
lengthCm = 500, // cm
widthCm = 200, // cm
axleLoadKg = 1500 // kg
)

// Define the route preferences with caravan profile and car transport mode
val routePreferences = RoutePreferences().apply {
this.truckProfile = caravanProfile
transportMode = ERouteTransportMode.Car // <- This field is crucial to distinguish caravan from truck
}

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

// Create routing service and calculate route
val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
// Handle results
}
)

val result = routingService.calculateRoute(waypoints)

At least one of the fields height, length, width or axleLoad must be set to a non-zero value in order for the settings to be taken into account during routing. If all these fields are set to 0 then a normal car route will be calculated.

Computing electric vehicle routes

To compute routes for electric vehicles, you can use the evProfile field of RoutePreferences:

// Create EV profile
val evProfile = EVProfile().apply {
name = "Tesla Model 3"
departureSoc = 0.8f // 80% charge at departure
destinationSoc = 0.2f // Minimum 20% charge at destination
batteryCapacity = 75000 // 75 kWh in Wh
vehicleRange = 500000 // 500 km in meters
efficiency = 150 // 150 Wh/km
fastCharge = 250 // 250 km per hour charging
ports = EEVChargingConnector.Type2.value or EEVChargingConnector.CSS2.value
}

// Define the route preferences with EV profile
val routePreferences = RoutePreferences().apply {
this.evProfile = evProfile
transportMode = ERouteTransportMode.Car
}

Setting departure heading

You can specify a departure heading to influence the initial direction of the route:

val routePreferences = RoutePreferences().apply {
// Set departure heading to 45 degrees with 25 degrees accuracy
setDepartureHeading(45.0, 25.0)
}

Building terrain profile and connections

To get detailed terrain information and route connections:

val routePreferences = RoutePreferences().apply {
// Enable terrain profile with minimum elevation variation
setBuildTerrainProfile(true, 5.0f) // 5 meters minimum variation

// Enable route connections with maximum connection length
setBuildConnections(true, 1000) // 1000 meters max connection length
}

Working with route ranges (Isochrones)

To calculate isochrone areas (reachable areas within specific time/distance):

val routePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Car
routeType = ERouteType.Fastest

// Set route ranges for isochrone calculation
// For fastest routes: values are in seconds
// For shortest routes: values are in meters
val ranges = arrayListOf(300, 600, 900) // 5, 10, 15 minutes
setRouteRanges(ranges, 80) // 80% quality
}

Public Transport routing

For public transport routes, you can configure specific PT preferences:

val routePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Public
algorithmType = EPTAlgorithmType.Departure
sortingStrategy = EPTSortingStrategy.BestTime
minimumTransferTimeInMinutes = 2
maximumTransferTimeInMinutes = 240
maximumWalkDistance = 1000 // 1 km
useWheelchair = true
useBikes = false

// Set route type preferences (combine multiple types with bitwise OR)
routeTypePreferences = EPTRouteTypePreference.Bus.value or
EPTRouteTypePreference.Underground.value
}

Calculate round trips

Generate routes that start and end at the same location using roundtrip parameters.

Key differences from normal routing:

  • Waypoint requirements - Normal routes require at least two waypoints. Roundtrips need only one departure point; additional waypoints are ignored. The algorithm generates multiple output waypoints automatically
  • Determinism - Normal routing produces the same route when inputs remain unchanged. Roundtrip generation is random by design, creating different routes each time. Use a seed value for deterministic results
  • Preferences - All normal routing preferences apply, including vehicle profiles and fitness factors

Range types

The ERangeType enumeration specifies units for the range parameter:

ERangeType valueDescription
DefaultUses DistanceBased for shortest routes; TimeBased for all other route types
DistanceBasedDistance measured in meters
TimeBasedDuration measured in seconds
(EnergyBased)Not currently supported
Tip

Specify DistanceBased or TimeBased explicitly to avoid confusion. A value of 10,000 means 10 km for distance-based requests but ~3 hours for time-based requests.

Roundtrip parameters

Configure roundtrips using RoundTripParameters:

ParameterTypeDescription
rangeIntTarget length or duration. The algorithm approximates this value but does not guarantee exact matches
rangeTypeERangeTypeUnits for the range value (distance or time)
randomSeedIntSet to 0 for random generation each time. Any other value produces deterministic results when other parameters remain unchanged

Create a round trip route

Set roundTripParameters in RoutePreferences with a non-zero range value:

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

// Define round trip preferences
val tripPreferences = RoundTripParameters(
range = 5000,
rangeType = ERangeType.DistanceBased,
randomSeed = 0 // 0 for random generation, other values for deterministic results
)

// Define route preferences to include round trip parameters
val routePreferences = RoutePreferences().apply {
transportMode = ERouteTransportMode.Bicycle
roundTripParameters = tripPreferences
}

// Create routing service and calculate round trip route
// Use only the departure landmark - additional waypoints are ignored
val routingService = RoutingService(
preferences = routePreferences,
onCompleted = { routes, errorCode, hint ->
if (errorCode == GemError.Success) {
// Handle successful round trip calculation
println("Number of routes: ${routes.size}")
} else {
// Handle error
println("Error calculating round trip: $errorCode - $hint")
}
}
)

val waypoints = arrayListOf(departureLandmark)
val result = routingService.calculateRoute(waypoints)
danger

If more than one waypoint is provided in a round trip calculation, only the first is considered; others are ignored.