Mapbox Navigation SDK for iOS

repository·main·Indexed 21 days ago

https://github.com/mapbox/mapbox-navigation-ios

A SDK for adding turn-by-turn navigation to iOS applications, featuring a drop-in NavigationViewController and core components for custom navigation experiences. Includes the mapbox-directions-swift command line tool for round-tripping JSON-formatted Directions or Map Matching API responses and generating GPX traces for the Xcode Simulator.

Tokens
3.5K
Snippets
11
Records
14
Agent score
74%

What's inside mapbox-navigation-ios

  1. Configure private token for Swift Package Manager

    main

    To install the SDK via Swift Package Manager, you must first configure a private access token with the DOWNLOADS:READ scope. This token is used by the package manager to download the SDK and is not your production API token.

    Warning: Do not insert this private token into any Info.plist file.

    1. Create or edit a .netrc file in your home directory.
    2. Add the following configuration to the file, replacing PRIVATE_MAPBOX_API_TOKEN with your token that has the DOWNLOADS:READ scope:
    machine api.mapbox.com
      login mapbox
      password PRIVATE_MAPBOX_API_TOKEN
  2. Build and run the Mapbox Directions Command Line Tool

    main

    The mapbox-directions-swift tool is a Swift package designed to round-trip JSON-formatted Directions or Map Matching API responses through model objects and back to JSON. This is useful for testing and designing API response processing pipelines.

    Build with SPM

    To build the MapboxDirectionsCLI target using Swift Package Manager:

    swift build --target "MapboxDirectionsCLI"

    Run and view usage

    To build (if necessary) and run the tool to see the help menu:

    swift run mapbox-directions-swift -h

    Run in Xcode

    To run the tool within Xcode, select the MapboxDirectionsCLI target and edit the scheme to include the necessary command-line arguments at launch.

    swift build --target "MapboxDirectionsCLI"
    swift run mapbox-directions-swift -h
  3. Configure Mapbox project settings and permissions

    main

    After installing the SDK, you must configure your iOS project to allow Mapbox services and background navigation to function:

    1. Access Token: In your application target's Info tab, under "Custom iOS Target Properties", set the key MBXAccessToken to your Mapbox access token.
    2. Location Permissions: In the Info tab, add the key NSLocationWhenInUseUsageDescription with a value such as: Shows your location on the map and helps improve the map.
    3. Background Modes: To ensure navigation and voice instructions continue when the app is in the background or the device is locked, go to the Signing & Capabilities tab and enable:
      • Audio, AirPlay, and Picture in Picture
      • Location updates (Alternatively, add audio and location to the UIBackgroundModes array in the Info tab.)
  4. Install Mapbox Navigation SDK via Swift Package Manager

    main

    For Applications

    1. In Xcode, go to File ‣ Swift Packages ‣ Add Package Dependency.
    2. Enter https://github.com/mapbox/mapbox-navigation-ios.git as the repository.
    3. Set Rules to Version, Up to Next Major, and enter 3.1.0 as the minimum version.

    For other Swift Packages

    Add the following dependency to your Package.swift file:

    // Latest stable release
    .package(url: "https://github.com/mapbox/mapbox-navigation-ios.git", from: "3.1.0")
  5. Configure Mapbox Directions CLI environment variables

    main

    The tool requires specific environment variables for authentication and endpoint routing:

    • MAPBOX_ACCESS_TOKEN: Set this to your Mapbox access token. This is required for certain operations.
    • MAPBOX_HOST: Set this to the base URL if you need to connect to an API endpoint other than the default Mapbox API endpoint.
  6. Use the mapbox-directions-swift CLI

    main

    The mapbox-directions-swift command line tool is designed to round-trip arbitrary, JSON-formatted Directions or Map Matching API responses through Mapbox model objects and back to JSON. It supports two primary subcommands: match for Map Matching data and route for Routing data.

    Authentication

    The tool requires a Mapbox access token. You can provide it via:

    1. The MAPBOX_ACCESS_TOKEN environment variable.
    2. The MBXAccessToken key in UserDefaults.

    You can also optionally specify a custom API host using the MAPBOX_HOST environment variable or the MGLMapboxAPIBaseURL key in UserDefaults.

    # Example usage for routing:
    # This takes a JSON file containing RouteOptions and outputs the result in GPX format
    ./mapbox-directions-swift route my_route_options.json --output result.gpx --format gpx
    
    # Example usage for map matching:
    # This takes a full Mapbox API request URL as the config argument
    ./mapbox-directions-swift match "https://api.mapbox.com/matching/v5/..." --output output.json
  7. Customize NavigationViewController appearance with custom styles

    main

    To blend the navigation UI with your application's design, you can create a custom style by subclassing StandardDayStyle (or other style classes) and passing it into the NavigationOptions when initializing the NavigationViewController.

    class CustomStandardDayStyle: StandardDayStyle {
        required init() {
            super.init()
            mapStyleURL = URL(string: "mapbox://styles/mapbox/satellite-streets-v9")!
            styleType = .night
        }
    
        override func apply() {
            BottomBannerView.appearance(for: UITraitCollection(userInterfaceIdiom: .phone)).backgroundColor = .orange
            BottomBannerView.appearance(for: UITraitCollection(userInterfaceIdiom: .pad)).backgroundColor = .orange
        }
    }
    
    // Usage
    let navigationOptions = NavigationOptions(
        mapboxNavigation: navigationProvider.mapboxNavigation,
        voiceController: navigationProvider.routeVoiceController,
        eventsManager: navigationProvider.eventsManager(),
        styles: [CustomStandardDayStyle()]
    )
    
    let navigationViewController = NavigationViewController(navigationRoutes: navigationRoutes, navigationOptions: navigationOptions)
  8. Convert a Directions API request using a URL

    main

    If you prefer to provide a URL instead of an input JSON file, use the --url flag along with your configuration file and input response file.

    swift run mapbox-directions-swift route -c < PATH TO CONFIG FILE (with your RouteOptions JSON) > \
    -f text \
    -i < PATH TO INPUT FILE (with your Directions API response) > \
    -u < URL REQUEST STRING >
  9. Use Mapbox Directions CLI for GPX trace generation

    main

    You can use this tool to generate a GPX trace from a Directions API response, which can then be used to simulate a route within the Xcode Simulator.

    Recipe for GPX trace generation:

    1. Provide a configuration file containing your RouteOptions JSON.
    2. Provide the input file containing the Directions API response.
    3. Specify the output filepath and set the format to gpx.
    swift run mapbox-directions-swift route -c < PATH TO CONFIG FILE (with your RouteOptions JSON) > \
    -f gpx \
    -i < PATH TO INPUT FILE (with your Directions API response) > \
    -o < PATH TO OUTPUT FILE >
  10. Implement turn-by-turn navigation with NavigationViewController

    main

    You can implement a full turn-by-turn navigation experience by calculating a route and presenting the NavigationViewController.

    This workflow involves:

    1. Initializing a MapboxNavigationProvider.
    2. Defining Waypoint objects for origin and destination.
    3. Using the routingProvider() to calculate routes.
    4. Passing the resulting navigationRoutes and NavigationOptions to a NavigationViewController.
    import MapboxDirections
    import MapboxNavigationCore
    import MapboxNavigationUIKit
    import UIKit
    import CoreLocation
    
    // 1. Define the Mapbox Navigation entry point
    let mapboxNavigationProvider = MapboxNavigationProvider(coreConfig: .init())
    lazy var mapboxNavigation = mapboxNavigationProvider.mapboxNavigation
    
    // 2. Define waypoints
    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")
    
    // 3. Request a route
    let options = NavigationRouteOptions(waypoints: [origin, destination])
    let request = mapboxNavigation.routingProvider().calculateRoutes(options: options)
    
    Task {
        switch await request.result {
        case .failure(let error):
            print(error.localizedDescription)
        case .success(let navigationRoutes):
            // 4. Present the NavigationViewController
            let navigationOptions = NavigationOptions(
                mapboxNavigation: mapboxNavigation,
                voiceController: mapboxNavigationProvider.routeVoiceController,
                eventsManager: mapboxNavigationProvider.eventsManager()
            )
            let navigationViewController = NavigationViewController(navigationRoutes: navigationRoutes,
                                                                    navigationOptions: navigationOptions)
            navigationViewController.modalPresentationStyle = .fullScreen
    
            present(navigationViewController, animated: true, completion: nil)
        }
    }
  11. Reference the Mapbox Directions CLI arguments and options

    main

    Arguments

    The tool accepts one primary argument:

    • A path to a JSON file containing serialized NavigationRouteOptions or NavigationMatchOptions.
    • A URL of a Mapbox Directions API or Mapbox Map Matching API request.

    Options

    OptionDescription
    --inputPath to the input JSON file. If omitted, the tool falls back to a Directions API request.
    --outputPath to save the conversion result. If omitted, results are printed to the shell. Use this to save GPX files for Xcode.
    --formatOutput format. Supported values: text, json, gpx.
    --urlA Directions API request URL string (alternative to using an input JSON file).