Planning a route
Requesting routes
To calculate a route from A to B, you need to provide route planning criteria. They are built using the RoutePlanningOptions
struct. There are multiple optional parameters that you can use to shape the route planning criteria to fit your use cases. For a detailed description of available parameters, see the Routing API, Calculate Route documentation.
1let amsterdamCoordinate = CLLocationCoordinate2DMake(52.3764527, 4.9062047)2let amsterdamAddress = Address(3 streetNumber: "30",4 streetName: "Basisweg",5 municipality: "Amsterdam",6 postalCode: "1043 AP",7 country: "The Netherlands"8)9let amsterdamPlace = Place(coordinate: amsterdamCoordinate, name: "Amsterdam", address: amsterdamAddress)10let berlinCoordinate = CLLocationCoordinate2DMake(52.5069751, 13.3631919)11let berlinPlace = Place(coordinate: berlinCoordinate, name: "Berlin")12let hagueCoordinate = CLLocationCoordinate2DMake(52.078663, 4.288788)13let hagueAddress = Address(14 streetNumber: "70",15 streetName: "De Perponcherstraat",16 municipality: "Den Haag",17 postalCode: "2518 SW",18 country: "The Netherlands"19)20let haguePlace = Place(coordinate: hagueCoordinate, name: "Den Haag", address: hagueAddress)2122let itinerary = Itinerary(23 origin: .init(place: amsterdamPlace),24 destination: .init(place: berlinPlace),25 waypoints: [.init(place: haguePlace)]26)2728let options: RoutePlanningOptions29do {30 options = try .init(31 itinerary: itinerary,32 costModel: .init(routeType: .efficient),33 vehicle: Car()34 )35} catch {36 print("Invalid planning options: \(error.localizedDescription)")37 return38}
Once you have a RoutePlanningOptions
object, pass it to the planRoute
method. The result of the planning is passed into the completion block passed to the 'planRoute' method. The result can be either .success(response)
if planning succeeded, or .failure(error)
if planning failed.
1routePlanner.planRoute(options: options, onRouteReady: nil) { result in2 switch result {3 case let .success(response):4 if (response.routes?.first) != nil {5 // success case6 }7 case .failure:8 // failure case9 break10 }11}
Adjusting route planning criteria
Route types
The routeType
parameter specifies the type of optimization used when calculating routes:
fast
- Route calculation is optimized by travel time, while keeping the routes sensible. For example, the calculation may avoid shortcuts along inconvenient side roads or long detours that only save very little time.short
- Route calculation is optimized so that a good compromise between small travel time and short travel distance is achieved.efficient
- Route calculation is optimized by fuel/energy consumption.thrilling
- Route calculation is optimized so that routes include interesting or challenging roads and use as few motorways as possible.- You can choose the level of turns included and also the degree of hilliness. See the
hilliness / windingness
parameters. - There is a limit of 900km on routes planned with
routeType=thrilling
.
- You can choose the level of turns included and also the degree of hilliness. See the
The default value is fast
.
Avoids
The AvoidOptions.avoids
parameter specifies something that the route calculation should try to avoid when determining the route. The avoid can be specified multiple times. Possible values are:
tollRoads
- Avoids toll roads.motorways
- Avoids motorways.ferries
- Avoids ferries.unpavedRoads
- Avoids unpaved roads.carpools
- Avoids routes that require the use of carpool (HOV/High Occupancy Vehicle) lanes.alreadyUsedRoads
- Avoids using the same road multiple times. This is important for round trips, when users may not want to use the same roads both ways. This is most useful in conjunction withrouteType=thrilling
.borderCrossings
- Avoids crossing country borders.tunnels
- Avoids tunnels.carTrains
- Avoids car trains.
Vehicle profile
Vehicle profile relates to a set of parameters that are used to provide extra information about the vehicle specification. It also provides information about the current state, e.g., the level of fuel.
Some roads in the map have vehicle and time dependent restrictions. For example, roads may restrict traffic to pedestrians, or can only be used by electric vehicles. Various road types may prohibit vehicles carrying hazardous materials. Tunnels may only be passable by vehicles up to a maximum height, and for trucks, with the proper tunnel code. These restrictions may affect the routes that can be planned for the user’s vehicle.
Key parameters defining vehicle profiles:
- Vehicle type, e.g., car or motorcycle.
- Engine type, e.g.,
combustion
orelectric
. For pedestrians and bicycles, no engine is allowed. - Consumption parameters used to adjust the overall range prediction of the vehicle.
- Vehicle dimensions.
- Hazardous payload describing the classification of carrying hazardous materials carried by the vehicle.
- Tunnel codes describing which tunnels can be used.
Vehicle profile properties are valid only at the current point in time and they get updated over time, e.g., the consumption curve. Vehicle profile is also useful during free driving mode without a route, e.g., to steer range features like a 360 range around the current position.
Guidance Mode
RoutePlanningOptions
uses the RouteInformationMode
enum to specify how much guidance information (instructions and lane guidance) is returned from the RoutePlanner.planRoute() function. The two options are complete
and firstIncrement
:
- With
complete
, theplanRoute
method returns a route with complete guidance information. - With
firstIncrement
,planRoute
returns a route with only the first guidance increment.
Planning errors
If any errors occurred during the planning, the result returned by the completion block will be .failure(error)
. The error type is NSError
for common errors (e.g., Networking) and RoutingError
for routing-specific errors. There are a few RoutingError
codes that are returned in different situations.
unknown
- Routing call ended with an unknown error.badInput
- The combination of input parameters was not valid.noRouteFound
- No valid route could be found.internalError
- The service encountered an unexpected error while fulfilling the request.cannotRestoreBaseroute
- The route could not be reconstructed usingsupportingPoints
.serviceUnavailable
- The service is not ready to handle the request.deserialization
- Deserialization of the routing response failed.network
- Routing network call failed.computationTimeout
-The request reached an internal computation time threshold and timed out.apiKeyError
- Indicates that the API key has no permission to access this resource.mapMatchingFailure
- One of the input points (origin, destination, waypoints) could not be matched to the map because no drivable section near this point could be found.cancelled
- The request has been cancelled.
Incremental guidance computation
Incremental guidance computation is an optimization technique that reduces route planning time. It works by initially providing the route with limited number of instructions and lane guidance rather then compute all instructions and lane guidance for the entire route.
The increment method requires RouteIncrementOptions
. RouteIncrementOptions
contains a Route
, RoutePlanningOptions
, and the boolean flag isDepartureInstructionRequired
which indicates whether to generate the first (departure) instruction.
The RouteInformationMode
enum contains two cases: complete
and firstIncrement
.
- The
complete
case is the default. In this mode, theplanRoute
method provides all instructions for the route immediately. - In the
firstIncrement
case, the route is generated with the first guidance increment. This takes less time than usingcomplete
mode.
The advanceGuidanceProgress
method is different from planRoute
in the following ways:
planRoute
creates a new route from the options passed as arguments. The computation results in either a route or an error.advanceGuidanceProgress
does not create a route. Instead, it works with an existing route, applying the planning options as it extends that route. TheadvanceGuidanceProgress
method returns either an updated version of existing route with new instructions and an updatedguidanceProgressOffset
value, or an error if the increment operation failed.