Swiftpack.co - Package - mapbox/mapbox-directions-swift

Mapbox Directions for Swift

CircleCI Carthage compatible CocoaPods CocoaPods SPM compatible codecov

Mapbox Directions for Swift (formerly MapboxDirections.swift) makes it easy to connect your iOS, macOS, tvOS, or watchOS application to the Mapbox Directions and Map Matching APIs. Quickly get driving, cycling, or walking directions, whether the trip is nonstop or it has multiple stopping points, all using a simple interface reminiscent of MapKit’s MKDirections API. Fit a GPX trace to the OpenStreetMap road network. The Mapbox Directions and Map Matching APIs are powered by the OSRM and Valhalla routing engines. For more information, see the Mapbox Navigation homepage.

Mapbox Directions pairs well with MapboxGeocoder.swift, MapboxStatic.swift, the Mapbox Navigation SDK for iOS, and the Mapbox Maps SDK for iOS or macOS SDK.

Getting started

Specify the following dependency in your Carthage Cartfile:

// Latest stable release
github "mapbox/mapbox-directions-swift" ~> 0.30
// Latest prerelease
github "mapbox/mapbox-directions-swift" ~> 1.0.0-alpha.1

Or in your CocoaPods Podfile:

# Latest stable release
pod 'MapboxDirections.swift', '~> 0.30'
# Latest prerelease
pod 'MapboxDirections', '~> v1.0.0-alpha.1'

Or in your Swift Package Manager Package.swift:

# Latest stable release
.package(url: "https://github.com/mapbox/mapbox-directions-swift.git", from: "0.30.0")
# Latest prerelease
.package(url: "https://github.com/mapbox/mapbox-directions-swift.git", from: "1.0.0-alpha.1")

Then import MapboxDirections.

This library supports a minimum deployment target of iOS 10.0 or above, macOS 10.12.0 or above, tvOS 10.0 or above, or watchOS 2.0 or above. v0.30.0 is the last release of MapboxDirections.swift that supports a minimum deployment target of iOS 9.x, macOS 10.11.x, tvOS 9.x, or watchOS 2.x. v0.30.0 is also the last release that is compatible with Objective-C or AppleScript code.

This repository contains an example application that demonstrates how to use the framework. To run it, you need to use Carthage 0.19 or above to install the dependencies. Detailed documentation is available in the Mapbox API Documentation.

Usage

API reference

You’ll need a Mapbox access token in order to use the API. If you’re already using the Mapbox Maps SDK for iOS or macOS SDK, Mapbox Directions automatically recognizes your access token, as long as you’ve placed it in the MGLMapboxAccessToken key of your application’s Info.plist file.

The examples below are each provided in Swift (denoted with main.swift), For further details, see the Mapbox Directions for Swift API reference.

Calculating directions between locations

The main directions class is Directions. Create a directions object using your access token:

// main.swift
import MapboxDirections

let directions = Directions(accessToken: "<#your access token#>")

Alternatively, you can place your access token in the MGLMapboxAccessToken key of your application’s Info.plist file, then use the shared directions object:

// main.swift
let directions = Directions.shared

With the directions object in hand, construct a RouteOptions object and pass it into the Directions.calculate(_:completionHandler:) method.

// main.swift

let waypoints = [
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox"),
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House"),
]
let options = RouteOptions(waypoints: waypoints, profileIdentifier: .automobileAvoidingTraffic)
options.includesSteps = true

let task = directions.calculate(options) { (waypoints, routes, error) in
    guard error == nil else {
        print("Error calculating directions: \(error!)")
        return
    }

    if let route = routes?.first, let leg = route.legs.first {
        print("Route via \(leg):")

        let distanceFormatter = LengthFormatter()
        let formattedDistance = distanceFormatter.string(fromMeters: route.distance)

        let travelTimeFormatter = DateComponentsFormatter()
        travelTimeFormatter.unitsStyle = .short
        let formattedTravelTime = travelTimeFormatter.string(from: route.expectedTravelTime)

        print("Distance: \(formattedDistance); ETA: \(formattedTravelTime!)")

        for step in leg.steps {
            print("\(step.instructions)")
            let formattedDistance = distanceFormatter.string(fromMeters: step.distance)
            print("— \(formattedDistance) —")
        }
    }
}

This library uses version 5 of the Mapbox Directions API by default. To use version 4 instead, replace RouteOptions with RouteOptionsV4.

Matching a trace to the road network

If you have a GPX trace or other GPS-derived location data, you can clean up the data and fit it to the road network using the Map Matching API:

// main.swift

let coordinates = [
    CLLocationCoordinate2D(latitude: 32.712041, longitude: -117.172836),
    CLLocationCoordinate2D(latitude: 32.712256, longitude: -117.17291),
    CLLocationCoordinate2D(latitude: 32.712444, longitude: -117.17292),
    CLLocationCoordinate2D(latitude: 32.71257,  longitude: -117.172922),
    CLLocationCoordinate2D(latitude: 32.7126,   longitude: -117.172985),
    CLLocationCoordinate2D(latitude: 32.712597, longitude: -117.173143),
    CLLocationCoordinate2D(latitude: 32.712546, longitude: -117.173345)
]

let options = MatchOptions(coordinates: coordinates)
options.includesSteps = true

let task = directions.calculate(options) { (matches, error) in
    guard error == nil else {
        print("Error matching coordinates: \(error!)")
        return
    }

    if let match = matches?.first, let leg = match.legs.first {
        print("Match via \(leg):")

        let distanceFormatter = LengthFormatter()
        let formattedDistance = distanceFormatter.string(fromMeters: match.distance)

        let travelTimeFormatter = DateComponentsFormatter()
        travelTimeFormatter.unitsStyle = .short
        let formattedTravelTime = travelTimeFormatter.string(from: match.expectedTravelTime)

        print("Distance: \(formattedDistance); ETA: \(formattedTravelTime!)")

        for step in leg.steps {
            print("\(step.instructions)")
            let formattedDistance = distanceFormatter.string(fromMeters: step.distance)
            print("— \(formattedDistance) —")
        }
    }
}

You can also use the Directions.calculateRoutes(matching:completionHandler:) method to get Route objects suitable for use anywhere a standard Directions API response would be used.

Usage with other Mapbox libraries

Drawing the route on a map

With the Mapbox Maps SDK for iOS or macOS SDK, you can easily draw the route on a map:

// main.swift

if var routeCoordinates = route.shape?.coordinates, routeCoordinates.count > 0 {
    // Convert the route’s coordinates into a polyline.
    let routeLine = MGLPolyline(coordinates: &routeCoordinates, count: UInt(routeCoordinates.count))

    // Add the polyline to the map.
    mapView.addAnnotation(routeLine)
    
    // Fit the viewport to the polyline.
    let camera = mapView.cameraThatFitsShape(routeLine, direction: 0, edgePadding: .zero)
    mapView.setCamera(camera, animated: true)
}

Displaying a turn-by-turn navigation interface

See the Mapbox Navigation SDK for iOS documentation for usage examples.

Tests

To run the included unit tests, you need to use Carthage 0.19 or above to install the dependencies.

  1. carthage build --platform iOS
  2. open MapboxDirections.xcodeproj
  3. Go to Product ‣ Test.

Github

link
Stars: 96

Used By

Total: 0

Releases

v1.0.0-alpha.1 - 2020-01-11 21:53:26

Changes since v0.30.0:

Packaging

  • Renamed MapboxDirections.swift to Mapbox Directions for Swift. The CocoaPods pod is now named MapboxDirections, matching the module name. (#400)
  • This library now requires a minimum deployment target of iOS 10.0 or above, macOS 10.12.0 or above, tvOS 10.0 or above, or watchOS 3.0 or above. Older operating system versions are no longer supported. (#379)
  • Swift is now required to directly use public types and methods defined by this library. If your application is written in Objective-C or Cocoa-AppleScript, you need to implement your own wrapper in Swift that bridges to Objective-C. (#382)
  • This library now depends on Turf. (#382)

Error handling

  • The RouteCompletionHandler and MatchCompletionHandler closures’ error argument is now a DirectionsError instead of an NSError. (#382)
  • Classes such as Route, Match, and RouteStep conform to the Codable protocol, so you can create instances of them from JSON-formatted Data using JSONDecoder and round-trip them back to JSON using JSONEncoder. Malformed input now throws decoding errors instead of crashing by unwrapping nils. (#382)

Visual instructions

  • Removed the Lane class in favor of storing an array of LaneIndications directly in the Intersection.approachLanes property. (#382)
  • Removed the ComponentRepresentable protocol, VisualInstructionComponent class, and LaneIndicationComponent class in favor of a VisualInstruction.Component enumeration that contains a VisualInstruction.Component.TextRepresentation and/or VisualInstruction.Component.ImageRepresentation, depending on the type of component. (#382)
  • Added the VisualInstruction.Component.ImageRepresentation.imageURL(scale:format:) method for fetching images with scales other than the current screen’s native scale or formats other than PNG. (#382)

Other changes

  • Removed support for Mapbox Directions API v4. (#382)
  • Replaced the MBDefaultWalkingSpeed, MBMinimumWalkingSpeed, and MBMaximumWalkingSpeed constants with CLLocationSpeed.normalWalking, CLLocationSpeed.minimumWalking, and CLLocationSpeed.maximumWalking, respectively.
  • Replaced the Route.coordinates property with Route.shape and the RouteStep.coordinates property with RouteStep.shape. The Route.coordinateCount and RouteStep.coordinateCount properties have been removed, but you can use the LineString.coordinates property to get the array of CLLocationCoordinate2Ds. (#382)
  • RouteLeg.source and RouteLeg.destination are now optional. They can be nil when the RouteLeg object is decoded individually from JSON. (#382)
  • Removed TransportType.none, ManeuverType.none, and ManeuverDirection.none. Unrecognized TransportType and ManeuverDirection values now raise decoding errors. (#382)
  • RouteStep.maneuverType is now optional. (#382)
  • Renamed the Tracepoint.alternateCount property to Tracepoint.countOfAlternatives. (#382)
  • The Intersection.approachIndex and Intersection.outletIndex properties are now optional, not −1, in the case of a departure or arrival maneuver. (#393)
  • Added initializers for Route, Match, RouteLeg, and RouteStep. (#393)
  • Various properties of Route, RouteLeg, and RouteStep are now writable. (#393)
  • Added AttributeOptions.maximumSpeedLimit for getting maximum posted speed limits in the RouteLeg.segmentMaximumSpeedLimits property. (#367)
  • Added the RouteLeg.segmentRangesByStep property for more easily associating RouteSteps with the values in segment-based arrays such as RouteLeg.segmentCongestionLevels. (#367)

Documentation is available online or within Xcode.

v0.30.0 - 2019-07-27 02:43:04

Changes since v0.29.0:

  • Directions.fetchAvailableOfflineVersions(completionHandler:) and Directions.downloadTiles(in:version:completionHandler:) now resumes the data task before returning it to conform to its naming conventions and avoid confusion. (#353)

Documentation is available online or within Xcode.

v0.29.0 - 2019-06-27 00:54:18

Changes since v0.28.0:

  • Added support for Swift Package Manager. (#362)

v0.28.0 - 2019-05-16 16:07:37

Changes since v0.27.3:

  • Added the RouteOptions.alleyPriority, RouteOptions.walkwayPriority, and RouteOptions.speed properties for fine-tuning walking directions. (#370)
  • Added the MBStringFromManeuverType(), MBStringFromManeuverDirection(), MBStringFromDrivingSide(), and MBStringFromTransportType() functions, which are intended for use in Objective-C. (#369)

Documentation is available online or within Xcode.

v0.27.3 - 2019-04-04 21:04:25

Changes since v0.27.2:

  • Fixed compatibility issues with Xcode 10.2 when the SDK is installed using Carthage. (#363)

Documentation is available online or within Xcode.

v0.27.2 - 2019-02-27 00:55:42

Changes since v0.27.1:

  • Fixed an issue where Waypoint.separatesLegs caused the resulting RouteLeg.source and RouteLeg.destination to have mismatched coordinates and names. (#358)
  • Fixed an issue where a Directions API or Map Matching API request would fail if a Waypoint has Waypoint.name set and Waypoint.separatesLegs set to false. (#358)

Documentation is available online or within Xcode.

v0.27.1 - 2019-02-23 00:55:33

Changes since v0.27.0:

Offline routing

  • Fixed an issue where Directions.downloadTiles(in:version:session:completionHandler:) always failed with an error after passing in a CoordinateBounds created using the CoordinateBounds(northWest:southEast:) initializer. (#349)
  • Added a CoordinateBounds(southWest:northEast:) initializer. (#349)
  • The versions passed into the completion handler of Directions.fetchAvailableOfflineVersions(completionHandler:) are now sorted in reverse chronological order. (#350)

Other changes

  • Fixed issues where VisualInstruction, VisualInstructionBanner, VisualInstructionComponent, LaneIndicationComponent, and RouteOptionsV4 objects failed to roundtrip through NSCoder. (#351)

Documentation is available online or within Xcode.

v0.27.0 - 2019-02-09 00:44:30

Changes since v0.26.1:

  • If a RouteOptions object has exceptionally many waypoints or if many of the waypoint have very long names, Directions.calculate(_:completionHandler:) sends a POST request to the Mapbox Directions API instead of sending a GET request that returns an error. (#341)
  • When possible, Directions.calculateRoutes(matching:completionHandler:) now sends a GET request to the Mapbox Map Matching API instead of a POST request. (#341)
  • Fixed an issue where certain waypoint names would cause Directions.calculateRoutes(matching:completionHandler:) to return an error. (#341)
  • Added the Directions.url(forCalculating:httpMethod:) and Directions.urlRequest(forCalculating:) methods for implementing custom GET- and POST-compatible request code. (#341)
  • Added the Waypoint.separatesLegs property, which you can set to false to create a route that travels “via” the waypoint but doesn’t stop there. Deprecated the MatchOptions.waypointIndices property in favor of Waypoint.separatesLegs, which also works with RouteOptions. (#340)
  • Fixed unset properties in Waypoint objects that are included in a calculated Routes or Matches. (#340)
  • Added DirectionsResult.fetchStartDate and DirectionsResult.requestEndDate properties. (#335)
  • Added a DirectionsOptions.urlQueryItems property so that subclasses of RouteOptions and MatchOptions can add any additional URL query parameters that are supported by the Mapbox Directions and Map Matching APIs. (#343)

Documentation is available online or within Xcode.

v0.26.1 - 2019-01-24 00:27:58

Changes since v0.26.0:

  • Waypoints and Tracepoints can now be compared for object equality. (#331)
  • Fixed an issue where the DirectionsResult.accessToken and DirectionsResult.apiEndpoint properties failed to roundtrip through NSCoder. (#331)
  • Route now supports secure coding via the NSSecureCoding protocol. (#331)
  • Fixed an issue where Intersection failed to decode when an outlet road has no road classes (i.e., a normal road that isn’t a bridge, tunnel, toll road, or motorway). (#331)

Documentation is available online or within Xcode.

v0.26.0 - 2018-12-20 10:01:09

Changes since v0.25.2:

  • Renamed CoordinateBounds(_:) to CoordinateBounds(coordinates:). (#325)
  • Added a Waypoint.targetCoordinate property for specifying a more specific destination for arrival instructions. (#326)
  • Fixed an issue where the Waypoint.allowsArrivingOnOppositeSide property was not copied when copying a Waypoint object. (#326)

Documentation is available online or within Xcode.

v0.25.2 - 2018-12-06 07:07:15

Changes since v0.25.1:

  • Fixed an issue where VisualInstructionComponent(json:) would set VisualInstructionComponent.imageURL to an invalid URL when the JSON representation includes an empty image URL. (#322)

Documentation is available online or within Xcode.

v0.25.1 - 2018-11-21 23:36:39

Changes since v0.25.0:

  • Added the Directions.apiEndpoint and Directions.accessToken properties that reflect the values passed into the Directions class’s initializers. (#313)
  • Fixed an issue causing some requests with many waypoints or long waypoint names to fail. (#311)
  • Fixed an issue where some requests with very many waypoints would fail silently. (#314)

Documentation is available online or within Xcode.

v0.25.0 - 2018-11-01 17:26:55

  • Added Directions.fetchAvailableOfflineVersions(completionHandler:) for listing available offline versions. (#303)
  • Added Directions.downloadTiles(in:version:session:completionHandler:) for downloading a tile pack. (#303)

v0.24.1 - 2018-10-23 19:39:05

Changes since v0.24.0:

  • Added RouteOptions.response(from:) which can be used for deserializing a response from an external source.

Documentation is available online or within Xcode.

v0.24.0 - 2018-10-01 02:10:12

Changes since v0.23.0:

  • DirectionsResult now includes the API response as JSON

Documentation is available online or within Xcode.

v0.23.0 - 2018-09-17 18:49:32

Changes since v0.22.0:

  • Added Waypoint.allowsArrivingOnOppositeSide property for restricting the side of arrival. (#288)

Documentation is available online or within Xcode.

v0.22.0 - 2018-07-11 21:27:42

Changes since v0.21.0:

  • Added the VisualInstructionBanner.tertiaryInstruction property for additional information to display, such as a lane configuration or subsequent turn. Renamed the VisualInstruction.textComponents property to VisualInstruction.components. Some of the components may be LaneIndicationComponent objects, representing a lane at an intersection. #258
  • Fixed a bug which caused coordinates to be off by a factor of 10 when requesting .polyline6 shape format. #281
  • Removed MBAttributeOpenStreetMapNodeIdentifier, as it is no longer being tracked by the API. This is a breaking change. #275

Documentation is available online or within Xcode.

v0.21.0 - 2018-05-09 22:59:37

Changes since v0.20.0:

  • Renamed VisualInstruction.degrees to VisualInstruction.finalHeading. https://github.com/mapbox/MapboxDirections.swift/pull/266
  • Removed support for MBAttributeOpenStreetMapNodeIdentifier. https://github.com/mapbox/MapboxDirections.swift/pull/272/
  • A named Waypoint will now be exposed in VisualInstructionComponent. https://github.com/mapbox/MapboxDirections.swift/pull/273

Documentation is available online or within Xcode.

v0.20.0 - 2018-04-12 16:21:01

Changes since v0.19.1:

  • Banner instructions object now includes a degrees field, corresponding to the location at which the user should exit a roundabout. #259

  • Also introduces a VisualInstructionBanner object which now contains the primary and secondary VisualInstruction objects. #259

Documentation is available online or within Xcode.

v0.19.1 - 2018-04-04 20:08:48

Changes since v0.19.0:

  • Fixed an issue that caused a warning when using Swift 4.1. #254, #255
  • Added types .exit and .exitCodes to MBVisualInstructionType. #252
  • Made an initializer on MBLane public. #253

Documentation is available online or within Xcode.

v0.19.0 - 2018-03-21 21:08:29

Changes since v0.18.0:

tl:dr

This release includes the ability to make a Mapbox Map Matching request.

Breaking changes

  • CompletionHandler has been renamed to RouteCompletionHandler to give room for MatchCompletionHandler.

Map Matching

  • Adds new class Match. A Match object defines a single route that was created from a series of points that were matched against a road network.
  • Adds new class MatchOptions. A MatchOptions object is a structure that specifies the criteria for results returned by the Mapbox Map Matching API.
  • Adds Directions.calculate(matchOptions:completionHandler:) which returns a Match.
  • Adds Directions.calculateRoutes(matching:completionHandler:). This is useful for creating a Route from a map matching request.

Documentation is available online or within Xcode.

- 2018-03-12 20:23:37

Changes since v0.17.0:

  • Adds support for abbreviations to VisualInstructionComponents. #244
  • Adds new types to VisualInstructionComponentType. #243

Documentation is available online or within Xcode.

- 2018-02-16 19:41:08

Changes since v0.16.1:

  • Adds ManeuverType and ManeuverDirection to VisualInstructionComponents (https://github.com/mapbox/MapboxDirections.swift/pull/239)

Documentation is available online or within Xcode.

v0.16.1 - 2018-02-13 20:53:04

Changes since v0.16.0:

  • RouteStep.drivingSide is now safely unwrapped for cases where the value is missing from the response. (#233)
  • Added .tunnel as a valid RoadClass. (#237)
  • Added .speechLocale to Route for deciphering which Locale to use for speaking voice instructions. (#235)

Documentation is available online or within Xcode.

v0.16.0 - 2018-01-17 23:14:20

Changes since v0.15.1:

  • The maneuverType, maneuverDirection, and transportType properties of RouteStep are now available in Objective-C code. The properties are no longer optional in Swift; check for ManeuverType.none ,ManeuverDirection.none, and TransportType.none instead of nil. (#227)

Documentation is available online or within Xcode.

v0.15.1 - 2017-12-08 23:03:16

Changes since v0.15.0:

  • API Response parser now handles API JSON response containing empty waypoint names correctly. (#222)

Documentation is available online or within Xcode.

- 2017-12-04 22:01:40

Changes since v0.14.0:

  • Added property drivingSide to RouteStep that indicates which side of the road cars and traffic flow. (#219)
  • Fixed a bug where named Waypoints were having their names stripped from the response. (#218)
  • Moved the class SpokenInstruction from private to open for easier testability. (#216)

Documentation is available online or within Xcode.

v0.14.0 - 2017-12-01 18:59:46

Changes since v0.13.0:

  • Added a RouteOption.roadClassesToAvoid property that avoids toll roads, motorways, or ferries. (#180)
  • The return value of Directions.calculate(_:completionHandler:) can be implicitly discarded. (#209)

Documentation is available online or within Xcode.

v0.13.0 - 2017-11-20 19:16:22

Changes since v0.12.1:

  • Upgrades the project to Swift 4. A final Swift 3.2 version is v0.12.1 and is also available on the branch swift3.2. #196

Documentation is available online or within Xcode.

v0.12.1 - 2017-11-10 19:20:54

Changes since v0.12.0:

  • Fixed an issue preventing Route objects archived prior to v0.12.0 from unarchiving. (#204)

Documentation is available online or within Xcode.