SDK for iOS Developer's Guide

Car and Pedestrian Routing

SDK for iOS supports route calculation with multiple waypoints optimized for walking or driving.

A route describes a path between at least two waypoints, the starting point and the destination, with optional intermediate waypoints in between. Applications can provide route information to users in two ways:
  • A line rendered on a map that displays a connecting path between all waypoints
  • Turn-by-turn directions in text format
Note: Routing backend has 1 year retention period, therefore for online routing functionality map has to be updated at least once a year. To update map data use [[NMAMapLoader sharedMapLoader] performMapDataUpdate] API.

Routing Example on GitHub

You can find an example that demonstrates this feature at https://github.com/heremaps/ (Obj-C) and https://github.com/heremaps/ (Swift).

NMACoreRouter

NMACoreRouter class is responsible for calculating an NMARoute using a list of stops and an NMARoutingMode. It also provides an NMACalculateResultBlock for monitoring calculation progress and triggering appropriate callback methods upon completion. To calculate a route, call calculateRouteWithStops:routingMode:completionBlock: method. You can launch parallel routing requests by using separate NMACoreRouter instances to launch calculation requests.

The NMACoreRouter can also calculate routes with traffic taken into account by setting dynamicPenalty property before launching a route calculation. For more information on the NMADynamicPenalty class see Dynamic Routing Penalty.

Note: NMACoreRouter variables must be strongly referenced and retained (e.g. made into a class member). Otherwise, the object may go out of scope and be garbage collected.

NMAWaypoint

The NMACoreRouter supports waypoints as NMAPlace, NMAPlaceLocation, or NMAWaypoint objects.

You can use NMAWaypoint to add more waypoint details to a car route calculation. These details include whether a waypoint is a deliberate stopover or a pass-through point that the route must pass through. This affects routing, as routes containing stopovers or pass-through waypoints may be different. For example, a calculated route may suggest a U-turn maneuver after a stopover, while a route containing the same location as a pass-through waypoint suggests continuing on the same street. The pass-through waypoint type is only supported in car routes and it is not supported in other route types.

NMARoutingMode

The NMARoutingMode class is a model of the parameters required to calculate an NMARoute such as:
  • routingType - the routing type, such as Fastest or Shortest
  • transportMode - the mode of transportation
  • routingOptions - the routing options (represented by NMARoutingOption enums) applicable for this route
  • startDirection - the direction of travel that the route should start in. By default this is set to "any direction" to achieve the fastest possible route
  • departureTime - the departure time for the route
  • resultLimit - the maximum number of alternate routes to calculate (the actual number of results may be fewer than this limit)
Note: Routing type describes different optimizations that can be applied during the route calculation:
  • Fastest - route calculation from start to destination optimized by travel time. In some cases the route returned by the fastest mode may not be the route with the shortest possible travel time. For example, it may favor a route that remains on a highway even if a shorter travel time can be achieved by taking a detour or shortcut through a side road.
  • Shortest - route calculation from start to destination disregarding any speed information. In this mode the distance of the route is minimized while keeping the route sensible. This includes, for example, penalizing turns. Because of that the resulting route will not necessarily be the one with minimal distance.
  • Balanced - route calculation from start to destination optimizing based on combination of travel time and distance.
Note: HERE SDK allows for more than one route to be returned from a route calculation between two waypoints. You can use the NMARoutingMode class to set the desired number of routes, and HERE SDK then returns different routes according to this limit. Note that the first element of the returned array is the best result based on the routing options, and the rest of the returned routes are not listed in any specific order.

NMARoute

The NMARoute class represents a distinct calculated path connecting two or more waypoints and consists of a list of maneuvers and route links. A call to calculateRouteWithStops:routingMode:completionBlock: method of NMACoreRouter triggers a route calculation while the returned NSProgress object and NMACalculateResultBlock block can be used to monitor the operation and process the resulting NMARoute objects.

An NMARoute object contains route information that can be accessed by calling one or more of the following methods:
  • routingMode - the NMARoutingMode for the route
  • waypoints - the array of all waypoints for the route
  • start - the starting waypoint for the route
  • destination - the destination waypoint for the route
  • maneuvers - the array of maneuvers for the route
  • length - the length of the route, in meters
  • ttaIncludingTrafficForSubleg - the NMARouteTta indicating the estimated time to arrival taking into account traffic conditions at the time of the route calculation
  • ttaUsingDownloadedTrafficForSubleg - the NMARouteTta indicating the estimated time to arrival with traffic conditions while the traffic conditions are taken from traffic data downloaded to the device
  • ttaExcludingTrafficForSubleg - the NMARouteTta indicating the estimated time to arrival without considering traffic conditions
  • boundingBox - gets the smallest NMAGeoBoundingBox that contains the entire route
  • routeGeometry - gets the array of all NMAGeoCoordinates along the route
  • mapPolyline - gets the NMAMapPolyline representation of the route

NMARouteTta

The NMARouteTta ("time-to-arrival") class provides useful information about the route such as duration and route details that impact travel duration including car pool restrictions, turn restrictions, and blocked roads. For example, to retrieve a duration for a calculated route, use tta property. For example,

NSTimeInterval duration = [route ttaExcludingTrafficForSubleg:NMARouteSublegWhole].duration;

You can also retrieve the duration for a subleg from a route by using ttaForSubleg: method. For example,

if (myRoute.sublegCount > 0)
{
  NSTimeInterval duration = [myRoute ttaExcludingTrafficForSubleg:0].duration;
}

Traffic-Aware Routing and NMARouteTta

The NMARoute class also provides ttaIncludingTrafficForSubleg and ttaUsingDownloadedTrafficForSubleg methods which provide a different set of NMARouteTta results that take traffic into account. If the route was originally calculated with setting a traffic penalty mode, ttaIncludingTrafficForSubleg method will return the estimated time to arrival with traffic conditions at the time of the route calculation. The value is calculated once at the time of route calculation and does not change with time. ttaUsingDownloadedTrafficForSubleg should be used in cases when the time elapsed since a route was returned is large enough to make the time to arrival (as obtained using ttaIncludingTrafficForSubleg) no longer accurate, given changing traffic conditions. ttaUsingDownloadedTrafficForSubleg will provide a more up-to-date time to arrival estimate provided traffic data has been constantly refreshed using the NMATrafficManager class.

Code snippet on how to use ttaIncludingTrafficForSubleg to get time to arrival considering traffic at the time the route was calculated.
...
NMADynamicPenalty *penalty = [[NMADynamicPenalty alloc] init];
penalty.trafficPenaltyMode = NMATrafficPenaltyModeOptimal;
coreRouter.dynamicPenalty = penalty;
[coreRouter calculateRouteWithStops:stops routingMode:routingMode
  completionBlock:^(NMARouteResult *routeResult, NMARoutingError error) { ... }];
NSTimeInterval duration = [route ttaIncludingTrafficForSubleg:NMARouteSublegWhole].duration;

If you have to calculate duration based on downloaded traffic data, you can also perform the following to request for traffic data to be populated:

[[NMATrafficManager sharedTrafficManager] requestTrafficOnRoute:route];
// Wait for the callback that the traffic data has been downloaded: trafficDataDidFinish
NSTimeInterval durationWithTraffic = [route ttaUsingDownloadedTrafficForSubleg:NMARouteSublegWhole].duration;
Note: A traffic-aware route calculation may return more violated options. For more information see Routing-related enumerations and the API Reference.

NMAManeuver

The NMAManeuver class represents the action required to go from one segment to the next within a calculated NMARoute. Each NMAManeuver object provides information such as:
  • location of the maneuver
  • action required to complete the maneuver
  • distance between maneuvers
  • current road
  • next road
  • estimated time of the maneuver
  • highway signpost (if any) indicating entrance, exit, or merge information
  • a list of route elements representing portions of this maneuver
For more information please consult the API Reference.

NMARouteElement and NMARoadElement

NMARouteElement and NMARoadElement represent portions within a maneuver. For example, a maneuver may ask the driver to turn left and then remain on a street but this street may be comprised of multiple sections including a tunnel, a dirt road, and a toll road. In this situation the maneuver contains multiple NMARouteElement objects, with each element containing an NMARoadElement property that can provide your application with information about the individual section of the road.

NMAMapRoute

The NMAMapRoute class is a type of NMAMapObject that displays a calculated route on a map. Typically, an application creates an NMAMapRoute after a route calculation and adds the NMAMapRoute to the map by calling NMAMapView addMapObject:.

You can customize map route colors by using renderType property and NMAMapRoute APIs. There are three supported render type values: NMAMapRouteRenderTypePrimary, NMAMapRouteRenderTypeSecondary, and NMAMapRouteRenderTypeUserDefined. By default, an NMAMapRoute is set to the Primary set of pre-defined colors, and the secondary render type is designed to denote alternate routes. By using NMAMapRouteRenderTypeUserDefined, you can use color and traveledColor properties and set the route colors to any ARGB color.

Figure 1. Using Primary RenderType
Figure 2. Using Secondary RenderType
Figure 3. User-Defined Route Color

For example, if you want to render a route that connects two waypoints (start and destination), you can add the following application logic:

Figure 4. An NMAMapRoute added to an NMAMapView
  1. Create an NMACoreRouter
    // Create a NMACoreRouter.
    NMACoreRouter* coreRouter = [[NMACoreRouter alloc] init];
  2. Create an NSMutableArray and add two NMAGeoCoordinates stops
    NMAGeoCoordinates* geoCoord1 = [[NMAGeoCoordinates alloc] initWithLatitude:49.1966286 longitude:-123.0053635];
    NMAGeoCoordinates* geoCoord2 = [[NMAGeoCoordinates alloc] initWithLatitude:49.1947289 longitude:-123.1762924];
    
    NMAWaypoint* waypoint1 = [[NMAWaypoint alloc] initWithGeoCoordinates:geoCoord1];
    NMAWaypoint* waypoint2 = [[NMAWaypoint alloc] initWithGeoCoordinates:geoCoord2];
    
    NSMutableArray* stops = [[NSMutableArray alloc] initWithCapacity:4];
    [stops addObject:waypoint1];
    [stops addObject:waypoint2];
  3. Create an NMARoutingMode and set its NMATransportMode, NMARoutingType, and NMARoutingOption values
    NMARoutingMode* routingMode = [[NMARoutingMode alloc]
        initWithRoutingType:NMARoutingTypeFastest
        transportMode:NMATransportModeCar
        routingOptions:0];
  4. If you want to calculate the route while taking traffic conditions into account, set the following flag:
    NMADynamicPenalty *penalty = [[NMADynamicPenalty alloc] init];
    penalty.trafficPenaltyMode = NMATrafficPenaltyModeOptimal;
    coreRouter.dynamicPenalty = penalty;
  5. Calculate the route and receive the results of the route calculation.
    [coreRouter calculateRouteWithStops:stops routingMode:routingMode
        completionBlock:^(NMARouteResult *routeResult, NMARoutingError error) {
    
          // If the route was calculated successfully
          if (!error && routeResult && routeResult.routes.count > 0)
          {
            NMARoute* route = [routeResult.routes objectAtIndex:0];
            // Render the route on the map
            NMAMapRoute* mapRoute = [NMAMapRoute mapRouteWithRoute:route];
            [mapView addMapObject:mapRoute];
    
            // To see the entire route, we orient the map view accordingly
            [mapView setBoundingBox:route.boundingBox
                    withAnimation:NMAMapAnimationLinear];
          }
          else if (error)
          {
            // Display a message indicating route calculation failure
          }
        }];
    
    Note: Routes are returned even if you receive NMARoutingErrorViolatesOptions error. It is up to you to handle these route results that violate routing options.

Dynamic Routing Penalty

You can use NMADynamicPenalty to create a policy of roads and area restriction factors applied during routing calculations. For example, you can use this class to indicate that the travel speed in an area is 50 percent slower than usual. The NMADynamicPenalty class also allows you to set the mode used for handling traffic events in a route calculation through trafficPenaltyMode property.

You can change the active policy by setting dynamicPenalty property in NMACoreRouter. The policy must be set before a route calculation for the restrictions to be taken into account.

Retrieving Traffic Event Objects

You can use the NMATrafficManager class to retrieve traffic events such as road closures or congestions. This is useful if your app needs to display a list of current traffic events for a given route.

Using NMATrafficManager is a two-step process. First, retrieve the events on the desired route using requestTrafficOnRoute: method:
NSNumber *requestID = [[NMATrafficManager sharedTrafficManager] requestTrafficOnRoute:myRoute];
requestTrafficOnRoute: method launches an asynchronous request to download the current traffic data to your device.
Note: Traffic data is also periodically downloaded when NMAMapView is set to display traffic. However, calling requestTrafficOnRoute: explicitly is recommended before retrieving traffic events using NMATrafficManager.
Upon the successful trafficDataDidFinish callback, you can retrieve a list of traffic events that affect the given route or route element by using one of the following methods:
  • getTrafficEventsOnRoute:withCompletion:
  • getTrafficEventsOnRouteElements:withCompletion:

Offline Routing

Even without an active data connection applications developed with SDK for iOS are able to request routing information to assist travelling from one location to another.

Your application users do not need to maintain an active data connection to calculate routes and render them on a map. It is possible to pre-download updated maps and database information for performing routing requests while offline. For example, if a user has downloaded offline maps of California and Oregon states, a route from San Diego to Portland can be created without any data connection.

For more information about downloading offline maps refer to Preloading Map Data.

Note: In HERE SDK v3.4 we have updated the behavior of routing connectivity modes (NMARequestConnectivity) to be more consistent with other parts of the SDK.
  • If you launch a request using the "default" connectivity mode, the request is performed according to NMAApplicationContext connectivity setting. If the device is offline while NMAApplicationContext is set to online mode, the request fails.
  • If you launch a request using the "online" connectivity mode, an online request is performed regardless of NMAApplicationContext connectivity setting.
  • If you launch a request using the "offline" connectivity mode, an offline request is performed regardless of NMAApplicationContext connectivity setting.
In all cases if the request fails, no fallback action is automatically performed.

Routing-Related Enumerations

Route calculations make use of HERE SDK enumerations that include:
  • NMARoutingType enum - represents values describing different routing types such as NMARoutingTypeFastest or NMARoutingTypeShortest
  • NMATransportMode enum - represents values describing different transport modes such as NMATransportModeCar or NMATransportModePedestrian
  • NMARoutingOption enum - represents values describing special conditions for route calculation such as NMARoutingOptionAvoidBoatFerry or NMARoutingOptionAvoidTollRoad. Values from this enum are also returned after a route calculation to indicate the options that a route result violates
  • NMARouteViolatedOption enum - represents values describing special conditions that are violated in a route calculation in addition to NMARoutingOption. This enum contains values for blocked roads and turn restrictions. For example, after specifying a route calculation that avoids tolls and ferries, you may get an NMARoute with NMARouteViolatedOptionBlockedRoad violated option. This indicates that although a route was found, this route goes through at least one blocked road — violating a condition of your route request
    Note: The absence of NMARouteViolatedOptionBlockedRoad does not necessarily indicate that no roads are blocked on a route. This is especially true when traffic information is unavailable or not enabled in the route calculation.
  • NMARoutingError enum - represents values describing possible route calculation errors such as NMARoutingErrorNone or NMARoutingErrorViolatesOptions