Mapbox Navigation SDK for iOS
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 Swift Package Manager
To install the MapboxNavigation framework in an application using Swift Package Manager:
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.In Xcode, go to File ‣ Swift Packages ‣ Add Package Dependency.
Enter
https://github.com/mapbox/mapbox-navigation-ios.git
as the package repository and click Next.Set Rules to Version, Up to Next Major, and enter
2.3.0
as the minimum version requirement. Click Next.
To install the MapboxCoreNavigation framework in another package rather than an application, run swift package init
to create a Package.swift, then add the following dependency:
// Latest prerelease
.package(name: "MapboxNavigation", url: "https://github.com/mapbox/mapbox-navigation-ios.git", from: "2.3.0")
Using CocoaPods
To install the MapboxNavigation framework using CocoaPods:
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.Create a Podfile with the following specification:
# Latest stable release pod 'MapboxNavigation', '~> 2.3' # Latest prerelease pod 'MapboxCoreNavigation', :git => 'https://github.com/mapbox/mapbox-navigation-ios.git', :tag => 'v2.3.0' pod 'MapboxNavigation', :git => 'https://github.com/mapbox/mapbox-navigation-ios.git', :tag => 'v2.3.0'
Run
pod repo update && pod install
and open the resulting Xcode workspace.
Configuration
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
MBXAccessToken
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.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.
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
andlocation
values to theUIBackgroundModes
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 strongSelf = self else {
return
}
// Pass the generated route response to the the NavigationViewController
let viewController = NavigationViewController(for: response, 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. PassiveLocationProvider
is an optional alternative to CLLocationManager
for use with any standalone MapView
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 that can be powered by the Mapbox Search SDK for iOS or 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 Notification
s 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 2.3.0
The v2.2.0 release notes clarified that is an error to have more than one instance of NavigationViewController
, NavigationService
, or RouteController
running simultaneously. Now you will receive a log message at the fault level helping you to spot the issue. To pause the debugger when the SDK detect the problematic situation, enable the “All Runtime Issues” breakpoint in Xcode. Learn more about breakpoints in Xcode documentation. (#3740)
Packaging
- MapboxNavigation now requires MapboxMaps v10.3.x. (#3748)
- MapboxCoreNavigation now requires MapboxDirections v2.3.x. (#3723)
- MapboxCoreNavigation now requires MapboxNavigationNative v88.x. (#3748)
Map
- Renamed the
NavigationMapView.highlightBuildings(at:in3D:completion:)
method toNavigationMapView.highlightBuildings(at:in3D:extrudeAll:completion:)
to provide the ability to extrude not only buildings at specific coordinates, but all other buildings as well. (#3736) - Added
MapView.showsTileSet(with:layerIdentifier:)
andMapView.setShowsTileSet(_:with:layerIdentifier:)
to provide the ability to show and hide custom tile set identifiers on the map view. (#3700) - Added the
NavigationMapView.mapViewTapGestureRecognizer
property and theNavigationMapView.legSeparatingWaypoints(on:closeTo:)
andNavigationMapView.routes(closeTo:)
methods for configuring how the map view responds to tap gestures when previewing a route. (#3746) - Fixed an issue where the route line and 3D building highlights disappeared from a standalone
NavigationMapView
when the map style changed. (#3734, #3736) - Fixed an issue where the route line blinked when refreshing the route. (#3647)
Visual instructions
- Renamed the
NextBannerView.update(for:)
,NextBannerView.show()
andNextBannerView.hide()
methods toNextBannerView.update(for:animated:duration:completion:)
,NextBannerView.show(animated:duration:completion:)
,NextBannerView.hide(animated:duration:completion:)
, respectively. (#3704) - Renamed the
LanesView.update(for:)
,LanesView.show()
andLanesView.hide()
methods toLanesView.update(for:animated:duration:completion:)
,LanesView.show(animated:duration:completion:)
,LanesView.hide(animated:duration:completion:)
, respectively. (#3704) - Added the
InstructionsCardContainerView.separatorColor
andInstructionsCardContainerView.highlightedSeparatorColor
to be able to change instruction card’s separator colors. (#3704) - Added
routeShieldRepresentationKey
to the user info dictionary ofNotification.Name.passiveLocationManagerDidUpdate
posted byPassiveLocationManager
, and theNotification.Name.currentRoadNameDidChange
posted byRouteController
. The corresponding value is aMapboxDirections.VisualInstruction.Component.ImageRepresentation
object representing the road shield the user is currently traveling on. (#3723) InstructionsCardViewController
now has a flat appearance. (#3704)- Fixed a crash when approaching an intersection in which one of the lanes is a merge lane. (#3699)
- Fixed an issue where the step list in
StepsViewController
is empty whle the user is on the final step of a route leg. (#3729) - Fixed the color of leg section headers in
StepsViewController
to switch between the day and night styles like the rest of the view controller. (#3760)
Location tracking
- Added an optional
datasetProfileIdentifier
argument to theMapboxRoutingProvider(_:settings:datasetProfileIdentifier:)
,PassiveLocationManager(directions:systemLocationManager:eventsManagerType:userInfo:datasetProfileIdentifier:),
TilesetDescriptorFactory.getSpecificVersion(version:completionQueue:datasetProfileIdentifier:completion:)
, andTilesetDescriptorFactory.getLatest(completionQueue:datasetProfileIdentifier:completion:)
methods for obtaining routing tiles optimized for a particular mode of transportation. Make sure to configureMapboxRoutingProvider
andTilesetDescriptorFactory
with the correct dataset profile if you customizeDirections.profileIdentifier
. (#3717) - Fixed a crash that sometimes occurred in Release configuration when initializing a
PassiveLocationManager
orRouteController
. (#3738) - Fixed an issue where the user location indicator floated around when the user was stopped at an intersection in an urban canyon. (#3705)
- Fixed poor location snapping while the user is inside a tunnel. (#3705)
- Fixed a leak of location tracking and routing resources after stopping all instances
RouteController
andPassiveLocationManager
. (#3724)
Offline routing
- If routing tiles in local storage are corrupted, the tiles are now redownloaded. (#3705)
- Offline routes now respect the
RouteOptions.roadClassesToAllow
property. (#3705) - Fixed an issue where
Directions.calculateOffline(options:completionHandler:)
calculated the route by making a network request. (#3702) - Fixed an issue where offline directions contained instructions in English regardless of the
DirectionsOptions.locale
property. (#3705)
Other changes
- Added
CarPlayUserInfo
type alias for storing CarPlay-related user information. This type will be used byCPRouteChoice
orCPListItem
while presenting trip with multiple route choices or when selecting list item from search results, respectively. (#3709) - Added the
CarPlayManagerDelegate.carPlayManagerDidEndNavigation(_:byCanceling:)
method, which is similar to the existingCarPlayManagerDelegate.carPlayManagerDidEndNavigation(_:)
method but indicates whether the user canceled the navigation session. (#3731) - Fixed an issue where changing
NavigationViewController.showsReportFeedback
,NavigationViewController.showsSpeedLimits
,NavigationViewController.detailedFeedbackEnabled
,NavigationViewController.floatingButtonsPosition
andNavigationViewController.floatingButtons
before presentingNavigationViewController
had no effect. (#3718) - Fixed an issue where
SpeechSynthesizing.managesAudioSession
was ignored byRouteVoiceController
. (#3572) - Fixed the gap between the end-of-route feedback panel and the bottom of the screen in landscape orientation. (#3769)