Mapbox Navigation SDK for iOS

Mapbox Navigation SDK

The Mapbox Navigation SDK gives you all the tools you need to add turn-by-turn navigation to your application. It takes just a few minutes to drop a full-fledged turn-by-turn navigation view controller into your application. Or use the Core Navigation framework directly to build something truly custom.

The Mapbox Navigation SDK and Core Navigation are compatible with applications written in Swift 5 in Xcode 10.2. The Mapbox Navigation and Mapbox Core Navigation frameworks run on iOS 10.0 and above.

Installation

Using CocoaPods

To install Mapbox Navigation using CocoaPods:

  1. Go to your Mapbox account dashboard and create an access token that has the DOWNLOADS:READ scope. PLEASE NOTE: This is not the same as your production Mapbox API token. Make sure to keep it private and do not insert it into any Info.plist file. Create a file named .netrc in your home directory if it doesn’t already exist, then add the following lines to the end of the file:

    machine api.mapbox.com 
     login mapbox
     password PRIVATE_MAPBOX_API_TOKEN
    

    where PRIVATE_MAPBOX_API_TOKEN is your Mapbox API token with the DOWNLOADS:READ scope.

  2. Create a Podfile with the following specification:

    pod 'MapboxCoreNavigation', :git => 'https://github.com/mapbox/mapbox-navigation-ios.git', :tag => '1.0'
    pod 'MapboxNavigation', :git => 'https://github.com/mapbox/mapbox-navigation-ios.git', :tag => '1.0'
    
  3. Run pod repo update && pod install and open the resulting Xcode workspace.

Using Carthage

Alternatively, to install Mapbox Navigation using Carthage:

  1. Go to your Mapbox account dashboard and create an access token that has the DOWNLOADS:READ scope. PLEASE NOTE: This is not the same as your production Mapbox API token. Make sure to keep it private and do not insert it into any Info.plist file. Create a file named .netrc in your home directory if it doesn’t already exist, then add the following lines to the end of the file:

    machine api.mapbox.com
     login mapbox
     password PRIVATE_MAPBOX_API_TOKEN
    

    where PRIVATE_MAPBOX_API_TOKEN is your Mapbox API token with the DOWNLOADS:READ scope.

  2. (Optional) Clear your Carthage caches:

    rm -rf ~/Library/Caches/carthage/ ~/Library/Caches/org.carthage.CarthageKit/binaries/{MapboxAccounts,MapboxCommon-ios,MapboxNavigationNative,mapbox-ios-sdk-dynamic}
    
  3. Create a Cartfile with the following dependency:

    github "mapbox/mapbox-navigation-ios" "1.0"
    

Configuration

  1. Mapbox APIs and vector tiles require a Mapbox account and API access token. In the project editor, select the application target, then go to the Info tab. Under the “Custom iOS Target Properties” section, set MGLMapboxAccessToken to your access token. You can obtain an access token from the Mapbox account page. Usage of Mapbox APIs is billed together based on monthly active users (MAU) rather than individually by HTTP request.

  2. In order for the SDK to track the user’s location as they move along the route, set NSLocationWhenInUseUsageDescription to:

    Shows your location on the map and helps improve the map.

  3. Users expect the SDK to continue to track the user’s location and deliver audible instructions even while a different application is visible or the device is locked. Go to the Signing & Capabilities tab. Under the Background Modes section, enable “Audio, AirPlay, and Picture in Picture” and “Location updates”. (Alternatively, add the audio and location values to the UIBackgroundModes array in the Info tab.)

Now import the relevant modules and present a new NavigationViewController. You can also push to a navigation view controller from within a storyboard if your application’s UI is laid out in Interface Builder.

import MapboxDirections
import MapboxCoreNavigation
import MapboxNavigation
// Define two waypoints to travel between
let origin = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox")
let destination = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House")

// Set options
let routeOptions = NavigationRouteOptions(waypoints: [origin, destination])

// Request a route using MapboxDirections
Directions.shared.calculate(routeOptions) { [weak self] (session, result) in
    switch result {
    case .failure(let error):
        print(error.localizedDescription)
    case .success(let response):
        guard let route = response.routes?.first, let strongSelf = self else {
            return
        }
        // Pass the generated route to the the NavigationViewController
        let viewController = NavigationViewController(for: route, routeIndex: 0, routeOptions: routeOptions)
        viewController.modalPresentationStyle = .fullScreen
        strongSelf.present(viewController, animated: true, completion: nil)
    }
}

Starting points

This SDK is divided into two frameworks: the Mapbox Navigation framework (MapboxNavigation) is the ready-made turn-by-turn navigation UI, while the Mapbox Core Navigation framework (MapboxCoreNavigation) is responsible for the underlying navigation logic.

Mapbox Navigation

NavigationViewController is the main class that encapsulates the entirety of the turn-by-turn navigation UI, orchestrating the map view, various UI elements, and the route controller. Your application would most likely present an instance of this class. The NavigationViewControllerDelegate protocol allows your application to customize various aspects of the UI and react to location-related events as they occur.

NavigationMapView is the map view at the center of the turn-by-turn navigation UI. You can also use this class independently of NavigationViewController, for example to display a route preview map. The NavigationMapViewDelegate protocol allows your application to customize various aspects of the map view’s appearance. PassiveLocationManager is an optional alternative to CLLocationManager for use with any standalone MGLMapView or NavigationMapView.

CarPlayManager is the class that manages the CarPlay screen if your application is CarPlay-enabled. It provides a main map for browsing, a search interface powered by MapboxGeocoder.swift, and a turn-by-turn navigation UI similar to the one provided by NavigationViewController. Your UIApplicationDelegate subclass can conform to the CarPlayManagerDelegate protocol to manage handoffs between NavigationViewController and the CarPlay device, as well as to customize some aspects of the CarPlay navigation experience. To take advantage of CarPlay functionality, your application must have a CarPlay navigation application entitlement and be built in Xcode 10 or above, and the user’s iPhone or iPad must have iOS 12 or above installed.

Core Navigation

MapboxNavigationService is responsible for receiving user location updates and determining their relation to the route line. If you build a completely custom navigation UI, this is the class your code would interact with directly. The NavigationServiceDelegate protocol allows your application to react to location-related events as they occur. Corresponding Notifications from the NavigationService‘s RouteController are also posted to the shared NotificationCenter. These notifications indicate the current state of the application in the form of a RouteProgress object.

For further details, consult the guides and examples included with this API reference. If you have any questions, please see our help page. We welcome your bug reports, feature requests, and contributions.

Changes in version 1.0.0

Packaging

  • Carthage v0.35 or above is now required for installing this SDK if you use Carthage. (81a36d0)
  • MapboxNavigation depends on Mapbox Maps SDK for iOS v6.0.0, and MapboxCoreNavigation depends on builds of MapboxNavigationNative and MapboxCommon that require authentication. Before CocoaPods or Carthage can download Mapbox.framework, MapboxNavigationNative.framework, and MapboxCommon.framework, you need to create a special-purpose access token. See the updated installation instructions in the readme for more details. (#2437, #2477)
  • If you install this SDK using Carthage, you need to also add MapboxCommon.framework to your application target’s Embed Frameworks build phase. (#2477)
  • Xcode 11.4.1 or above is now required for building this SDK from source. (#2417)
  • By default, usage of Mapbox APIs is now billed together based on monthly active users rather than individually by HTTP request. If you prefer to still use request-based billing, set the MBXNavigationBillingMethod key in Info.plist to request. (#2405)
  • Added Greek and Turkish localizations. (#2385, #2475)
  • Upgraded to MapboxDirections v1.0.0, MapboxSpeech v1.0.0, and Turf v1.0.0. (#2646)

Map

Visual and spoken instructions

  • As the user approaches certain junctions, an enlarged illustration of the junction appears below the top banner to help the user understand a complex maneuver. These junction views only appear when the relevant data is available. Contact your Mapbox sales representative or support team for access to the junction views feature. (#2408)
  • Replaced RouteVoiceController and MapboxVoiceController with MultiplexedSpeechSynthesizer. MultiplexedSpeechSynthesizer coordinates multiple cascading speech synthesizers. By default, the controller still tries to speak instructions via the Mapbox Voice API (MapboxSpeechSynthesizer) before falling back to VoiceOver (SystemSpeechSynthesizer), but you can also provide your own speech synthesizer that conforms to the SpeechSynthesizing protocol. (#2348)
  • Added an alternative presentation for maneuver instructions that resembles swipeable user notification cards. To replace the conventional TopBannerViewController presentation with the cardlike presentation, create an instance of InstructionsCardViewController and pass it into the NavigationOptions(styles:navigationService:voiceController:topBanner:bottomBanner:) method. (#2149, #2296, #2627)

Feedback

User location

  • Improved the accuracy of location tracking and off-route detection. (#2319)
  • Added the PassiveLocationManager class for use with the MGLMapView.locationManager property. Unlike CLLocationManager, this class causes the map view to display user locations snapped to the road network, just like during turn-by-turn navigation. To receive these locations without an MGLMapView, use the PassiveLocationDataSource class and implement the PassiveLocationDataSourceDelegate.passiveLocationDataSource(_:didUpdateLocation:rawLocation:) method or observe Notification.Name.passiveLocationDataSourceDidUpdate notifications. (#2410)
  • The NavigationViewController.route and NavigationService.route properties are now read-only. To change the route that the user is traveling along, set the NavigationViewController.indexedRoute or NavigationService.indexedRoute property instead, pairing the route with the index of the route in the original RouteResponse object. (#2366)
  • The following methods now require a route index to be passed in as an argument (#2366):
    • NavigationViewController(for:routeIndex:routeOptions:navigationOptions:)
    • NavigationViewController(route:routeIndex:routeOptions:navigationService:)
    • CarPlayManagerDelegate.carPlayManager(_:navigationServiceAlong:routeIndex:routeOptions:desiredSimulationMode:)
    • MapboxNavigationService(route:routeIndex:routeOptions:)
    • MapboxNavigationService(route:routeIndex:routeOptions:directions:locationSource:eventsManagerType:simulating:routerType:)
    • RouteProgress(route:routeIndex:options:legIndex:spokenInstructionIndex:)
    • RouteProgress(route:routeIndex:options:legIndex:spokenInstructionIndex:)
    • Router(along:routeIndex:options:directions:dataSource:)
    • RouteController(along:routeIndex:options:directions:dataSource:)
  • Fixed an issue where location tracking would pause at the beginning of a route after setting RouteOptions.shapeFormat to RouteShapeFormat.polyline or RouteShapeFormat.geoJSON. Note that you most likely do not need to override the default value of RouteShapeFormat.polyline6: this is the least bandwidth-intensive format, and Route.shape and RouteStep.shape are set to LineStrings regardless. (#2319)
  • Fixed an issue where various delegate methods omitted CLLocation.courseAccuracy and CLLocation.speedAccuracy properties from passed-in CLLocation objects when using RouteController, even when these properties are provided by Core Location on iOS 13.4 and above. (#2417)
  • Fixed issues where the user puck would sometimes drift away from the route line even though the user was following the route. (#2412, #2417)
  • Fixed an issue where RouteController took longer than usual to detect that the user had gone off-route. (#2412)
  • Fixed an issue where RouteController would detect that the user had gone off-route due to a single errant location update. (#2412, #2417)
  • Fixed an issue where the camera and user puck would cut a corner when making a turn at speed. (#2412)
  • Fixed an issue where RouteController became too sensitive to the user going off-route near “intersections” that the Mapbox Directions API synthesizes at road classification changes, such as at either end of a tunnel. (#2412)
  • If the user’s raw course as reported by Core Location differs significantly from the direction of the road ahead, the camera and user puck are oriented according to the raw course. (#2417)
  • RouteController now tracks the user’s location more accurately within roundabouts. (#2417)
  • Fixed an issue where departure instructions were briefly missing when beginning turn-by-turn navigation. (#2417)
  • Removed the RouteController.projectedLocation(for:) method in favor of RouteController.location. It is no longer possible to predict the user’s location at an arbitrary time. (#2610)
  • Renamed the Router.advanceLegIndex(location:) method to Router.advanceLegIndex(). It is no longer possible to advance to an arbitrary leg using this method. (#2610)

Other changes

  • The RouteProgress.congestionTravelTimesSegmentsByStep and RouteProgress.congestionTimesPerStep properties are now read-only. (#2624)
  • Deprecated NavigationDirectionsCompletionHandler, OfflineRoutingError, UnpackProgressHandler, UnpackCompletionHandler, OfflineRouteCompletionHandler, and NavigationDirections. Use Directions instead of NavigationDirections to calculate a route. (#2509)
  • The RouteLegProgress.congestionTravelTimesSegmentsByStep and RouteLegProgress.congestionTimesPerStep properties are now read-only. (#2615)