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: ItineraryPoint(place: amsterdamPlace),24 destination: ItineraryPoint(place: berlinPlace),25 waypoints: [ItineraryPoint(place: haguePlace)]26)2728let options: RoutePlanningOptions29do {30 options = try RoutePlanningOptions(31 itinerary: itinerary,32 costModel: CostModel(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 OnlineRoutePlanner.planRoute(options:onRouteReady:completion:)
method. The result of the planning is passed into the completion of the abovementioned method. The result can be either Result.success(_:)
if planning succeeded, or Result.failure(_:)
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
type specifies the kind of optimization used when calculating routes:
RouteType.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.RouteType.short
- Route calculation is optimized so that a good compromise between small travel time and short travel distance is achieved.RouteType.efficient
- Route calculation is optimized by fuel/energy consumption.RouteType.thrilling(hilliness:windingness:)
- 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
andwindingness
parameters. - There is a limit of 900km on routes planned with
RouteType.thrilling(hilliness:windingness:)
.
- You can choose the level of turns included and also the degree of hilliness. See the
The default value is RouteType.fast
.
Avoids
The AvoidOptions.avoids
parameter specifies something that the route calculation should try to avoid when determining the route. Avoids are honored whenever a reasonable alternative is available that fulfills all avoidance criteria. If the detour becomes too large, some avoidance criteria can be violated on parts of the route. The violations can be detected by checking the corresponding route sections.
The avoid can be specified multiple times. Possible values are:
AvoidType.tollRoads
- Avoids toll roads.AvoidType.motorways
- Avoids motorways.AvoidType.ferries
- Avoids ferries.AvoidType.unpavedRoads
- Avoids unpaved roads.AvoidType.carpools
- Avoids routes that require the use of carpool (HOV/High Occupancy Vehicle) lanes.AvoidType.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
set toRouteType.thrilling(hilliness:windingness:)
.AvoidType.borderCrossings
- Avoids crossing country borders.AvoidType.tunnels
- Avoids tunnels.AvoidType.carTrains
- Avoids car trains.AvoidType.lowEmissionZones
- Avoids low-emission zones.
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 on 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.,
EngineType.combustion
orEngineType.electric
. For pedestrians and bicycles, no engine is allowed. - Consumption parameters are 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. The vehicle profile is also useful during free driving mode without a route, e.g., to steer range features like a 360-degree 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(options:onRouteReady:completion:)
function. The two options are RouteInformationMode.complete
and RouteInformationMode.firstIncrement
:
- With
RouteInformationMode.complete
, theRoutePlanner.planRoute(options:onRouteReady:completion:)
method returns a route with complete guidance information. - With
RouteInformationMode.firstIncrement
,RoutePlanner.planRoute(options:onRouteReady:completion:)
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 Result.failure(_:)
. 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.
RoutingError.Code.unknown
- Routing call ended with an unknown error.RoutingError.Code.badInput
- The combination of input parameters was not valid.RoutingError.Code.noRouteFound
- No valid route could be found.RoutingError.Code.internalError
- The service encountered an unexpected error while fulfilling the request.RoutingError.Code.cannotRestoreBaseroute
- The route could not be reconstructed usingRouteLegOptions.supportingPoints
.RoutingError.Code.serviceUnavailable
- The service is not ready to handle the request.RoutingError.Code.deserialization
- Deserialization of the routing response failed.RoutingError.Code.network
- Routing network call failed.RoutingError.Code.computationTimeout
-The request reached an internal computation time threshold and timed out.RoutingError.Code.apiKeyError
- Indicates that the API key has no permission to access this resource.RoutingError.Code.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.RoutingError.Code.cancelled
- The request has been canceled.
Incremental guidance computation
Incremental guidance computation is an optimization technique that reduces route planning time. It works by initially providing the route with a limited number of instructions and lane guidance rather than computing all instructions and lane guidance for the entire route.
The increment method requires RouteIncrementOptions
. RouteIncrementOptions
contains a Route
, RoutePlanningOptions
, and the boolean flag RoutePlanningOptions.isDepartureInstructionRequired
which indicates whether to generate the first (departure) instruction.
The RouteInformationMode
enum contains two cases: RouteInformationMode.complete
and RouteInformationMode.firstIncrement
.
- The
RouteInformationMode.complete
case is the default. In this mode, theRoutePlanner.planRoute(options:onRouteReady:completion:)
method provides all instructions for the route immediately. - In the
RouteInformationMode.firstIncrement
case, the route is generated with the first guidance increment. This takes less time than usingRouteInformationMode.complete
mode.
The RoutePlanner.advanceGuidanceProgress(with:)
method is different from RoutePlanner.planRoute(options:onRouteReady:completion:)
in the following ways:
RoutePlanner.planRoute(options:onRouteReady:completion:)
creates a new route from the options passed as arguments. The computation results in either a route or an error.RoutePlanner.advanceGuidanceProgress(with:)
does not create a route. Instead, it works with an existing route, applying the planning options as it extends that route. TheRoutePlanner.advanceGuidanceProgress(with:)
method returns either an updated version of the existing route with new instructions and an updatedRoutePlanner.advanceGuidanceProgress(with:)
value, or an error if the increment operation failed.
Next steps
Since you have learned how to plan a route, here are recommendations for the next steps: