{"id":13588344,"url":"https://github.com/mapbox/mapbox-directions-swift","last_synced_at":"2025-05-15T20:05:35.681Z","repository":{"id":24169511,"uuid":"27559880","full_name":"mapbox/mapbox-directions-swift","owner":"mapbox","description":"Traffic-aware directions and map matching in Swift on iOS, macOS, tvOS, watchOS, and Linux","archived":false,"fork":false,"pushed_at":"2025-02-06T11:16:56.000Z","size":70031,"stargazers_count":193,"open_issues_count":37,"forks_count":93,"subscribers_count":125,"default_branch":"main","last_synced_at":"2025-04-21T08:56:52.845Z","etag":null,"topics":["directions","ios","linux","macos","map-matching","mapbox-directions","navigation","openstreetmap","osrm","routing","swift","traffic","tvos","valhalla","watchos"],"latest_commit_sha":null,"homepage":"https://www.mapbox.com/navigation/","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"edsomjr/TEP","license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mapbox.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-12-04T21:01:09.000Z","updated_at":"2025-04-04T04:23:01.000Z","dependencies_parsed_at":"2023-01-16T22:45:36.682Z","dependency_job_id":"1afe24ae-1180-410d-95a8-9b906690524e","html_url":"https://github.com/mapbox/mapbox-directions-swift","commit_stats":{"total_commits":1364,"total_committers":51,"mean_commits":"26.745098039215687","dds":0.6202346041055719,"last_synced_commit":"9714ec6451bec68ce7a753b8070a0b5664019a1c"},"previous_names":["mapbox/mapboxdirections.swift"],"tags_count":136,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fmapbox-directions-swift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fmapbox-directions-swift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fmapbox-directions-swift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mapbox%2Fmapbox-directions-swift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mapbox","download_url":"https://codeload.github.com/mapbox/mapbox-directions-swift/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254414499,"owners_count":22067272,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["directions","ios","linux","macos","map-matching","mapbox-directions","navigation","openstreetmap","osrm","routing","swift","traffic","tvos","valhalla","watchos"],"created_at":"2024-08-01T15:06:39.125Z","updated_at":"2025-05-15T20:05:30.602Z","avatar_url":"https://github.com/mapbox.png","language":"Swift","readme":"# Mapbox Directions for Swift\n\n[![CircleCI](https://circleci.com/gh/mapbox/mapbox-directions-swift.svg?style=svg)](https://circleci.com/gh/mapbox/mapbox-directions-swift)\n[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)\n[![CocoaPods](https://img.shields.io/cocoapods/v/MapboxDirections.svg)](https://cocoapods.org/pods/MapboxDirections/)\n[![SPM compatible](https://img.shields.io/badge/SPM-compatible-4BC51D.svg?style=flat)](https://swift.org/package-manager/)\n\nMapbox Directions for Swift (formerly MapboxDirections.swift) makes it easy to connect your iOS, macOS, tvOS, watchOS, or Linux application to the [Mapbox Directions](https://docs.mapbox.com/api/navigation/) and [Map Matching](https://docs.mapbox.com/api/navigation/#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](https://www.openstreetmap.org/) road network. The Mapbox Directions and Map Matching APIs are powered by the [OSRM](http://project-osrm.org/) and [Valhalla](https://github.com/valhalla/valhalla/) routing engines. For more information, see the [Mapbox Navigation](https://www.mapbox.com/navigation/) homepage.\n\nMapbox Directions pairs well with [MapboxGeocoder.swift](https://github.com/mapbox/MapboxGeocoder.swift), [MapboxStatic.swift](https://github.com/mapbox/MapboxStatic.swift), the [Mapbox Navigation SDK for iOS](https://github.com/mapbox/mapbox-navigation-ios/), and the [Mapbox Maps SDK for iOS](https://docs.mapbox.com/ios/maps/) or [macOS SDK](https://mapbox.github.io/mapbox-gl-native/macos/).\n\n## Getting started\n\nSpecify the following dependency in your [Carthage](https://github.com/Carthage/Carthage) Cartfile:\n\n```cartfile\n# Latest stable release\ngithub \"mapbox/mapbox-directions-swift\" ~\u003e 2.14\n# Latest prerelease\ngithub \"mapbox/mapbox-directions-swift\" \"v2.11.0-alpha.1\"\n```\n\nOr in your [CocoaPods](http://cocoapods.org/) Podfile:\n\n```podspec\n# Latest stable release\npod 'MapboxDirections', '~\u003e 2.14'\n# Latest prerelease\npod 'MapboxDirections', :git =\u003e 'https://github.com/mapbox/mapbox-directions-swift.git', :tag =\u003e 'v2.11.0-alpha.1'\n```\n\nOr in your [Swift Package Manager](https://swift.org/package-manager/) Package.swift:\n\n```swift\n// Latest stable release\n.package(name: \"MapboxDirections\", url: \"https://github.com/mapbox/mapbox-directions-swift.git\", from: \"2.14.0\")\n// Latest prerelease\n.package(name: \"MapboxDirections\", url: \"https://github.com/mapbox/mapbox-directions-swift.git\", .exact(\"2.11.0-alpha.1\"))\n```\n\nThen `import MapboxDirections`.\n\nThis repository contains an example application that demonstrates how to use the framework. To run it, you need to use [Carthage](https://github.com/Carthage/Carthage) 0.19 or above to install the dependencies. Detailed documentation is available in the [Mapbox API Documentation](https://docs.mapbox.com/api/navigation/#directions).\n\n## System requirements\n\n* One of the following package managers:\n   * CocoaPods 1.10 or above\n   * Carthage 0.38 or above\n   * Swift Package Manager 5.5 or above\n* Xcode 13 or above\n* One of the following operating systems:\n   * iOS 12.0 or above\n   * macOS 10.14 or above\n   * tvOS 12.0 or above\n   * watchOS 5.0 or above\n   * Any Linux distribution supported by Swift\n\nv0.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.\n\n## Usage\n\n**[API reference](https://docs.mapbox.com/ios/api/directions/)**\n\nYou’ll need a [Mapbox access token](https://docs.mapbox.com/api/#access-tokens-and-token-scopes) in order to use the API. If you’re already using the [Mapbox Maps SDK for iOS](https://docs.mapbox.com/ios/maps/) or [macOS SDK](https://mapbox.github.io/mapbox-gl-native/macos/), Mapbox Directions automatically recognizes your access token, as long as you’ve placed it in the `MBXAccessToken` key of your application’s Info.plist file.\n\nThe examples below are each provided in Swift (denoted with `main.swift`). For further details, see the documentation available by the link in the [releases](https://github.com/mapbox/mapbox-directions-swift/releases).\n\n### Calculating directions between locations\n\nThe main directions class is `Directions`. Create a directions object using your access token:\n\n```swift\n// main.swift\nimport MapboxDirections\n\nlet directions = Directions(credentials: Credentials(accessToken: \"\u003c#your access token#\u003e\"))\n```\n\nAlternatively, you can place your access token in the `MBXAccessToken` key of your application’s Info.plist file, then use the shared directions object:\n\n```swift\n// main.swift\nlet directions = Directions.shared\n```\n\nWith the directions object in hand, construct a RouteOptions object and pass it into the `Directions.calculate(_:completionHandler:)` method.\n\n```swift\n// main.swift\n\nlet waypoints = [\n    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: \"Mapbox\"),\n    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: \"White House\"),\n]\nlet options = RouteOptions(waypoints: waypoints, profileIdentifier: .automobileAvoidingTraffic)\noptions.includesSteps = true\n\nlet task = directions.calculate(options) { (session, result) in\n    switch result {\n    case .failure(let error):\n        print(\"Error calculating directions: \\(error)\")\n    case .success(let response):\n        guard let route = response.routes?.first, let leg = route.legs.first else {\n            return\n        }\n\n        print(\"Route via \\(leg):\")\n\n        let distanceFormatter = LengthFormatter()\n        let formattedDistance = distanceFormatter.string(fromMeters: route.distance)\n\n        let travelTimeFormatter = DateComponentsFormatter()\n        travelTimeFormatter.unitsStyle = .short\n        let formattedTravelTime = travelTimeFormatter.string(from: route.expectedTravelTime)\n\n        print(\"Distance: \\(formattedDistance); ETA: \\(formattedTravelTime!)\")\n\n        for step in leg.steps {\n            print(\"\\(step.instructions)\")\n            let formattedDistance = distanceFormatter.string(fromMeters: step.distance)\n            print(\"— \\(formattedDistance) —\")\n        }\n    }\n}\n```\n\nThis library uses version 5 of the Mapbox Directions API by default.\n\n### Matching a trace to the road network\n\nIf 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:\n\n```swift\n// main.swift\n\nlet coordinates = [\n    CLLocationCoordinate2D(latitude: 32.712041, longitude: -117.172836),\n    CLLocationCoordinate2D(latitude: 32.712256, longitude: -117.17291),\n    CLLocationCoordinate2D(latitude: 32.712444, longitude: -117.17292),\n    CLLocationCoordinate2D(latitude: 32.71257,  longitude: -117.172922),\n    CLLocationCoordinate2D(latitude: 32.7126,   longitude: -117.172985),\n    CLLocationCoordinate2D(latitude: 32.712597, longitude: -117.173143),\n    CLLocationCoordinate2D(latitude: 32.712546, longitude: -117.173345)\n]\n\nlet options = MatchOptions(coordinates: coordinates)\noptions.includesSteps = true\n\nlet task = directions.calculate(options) { (session, result) in\n    switch result {\n    case .failure(let error):\n        print(\"Error matching coordinates: \\(error)\")\n    case .success(let response):\n        guard let match = response.matches?.first, let leg = match.legs.first else {\n            return\n        }\n\n        print(\"Match via \\(leg):\")\n\n        let distanceFormatter = LengthFormatter()\n        let formattedDistance = distanceFormatter.string(fromMeters: match.distance)\n\n        let travelTimeFormatter = DateComponentsFormatter()\n        travelTimeFormatter.unitsStyle = .short\n        let formattedTravelTime = travelTimeFormatter.string(from: match.expectedTravelTime)\n\n        print(\"Distance: \\(formattedDistance); ETA: \\(formattedTravelTime!)\")\n\n        for step in leg.steps {\n            print(\"\\(step.instructions)\")\n            let formattedDistance = distanceFormatter.string(fromMeters: step.distance)\n            print(\"— \\(formattedDistance) —\")\n        }\n    }\n}\n```\n\nYou 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.\n\n### Build an isochrone map\n\nTell the user how far they can travel within certain distances or times of a given location using the Isochrone API. `Isochrones` uses the same access token initialization as `Directions`. Once that is configured, you need to fill `IsochronesOptions` parameters to calculate the desired GeoJSON:\n\n```swift\nlet isochrones = Isochrones(credentials: Credentials(accessToken: \"\u003c#your access token#\u003e\"))\n\nlet isochroneOptions = IsochroneOptions(centerCoordinate: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),\n                                        contours: .byDistances([\n                                            .init(value: 500, unit: .meters,     color: .orange),\n                                            .init(value: 1,   unit: .kilometers, color: .red)\n                                        ]))\n\nisochrones.calculate(isochroneOptions) { session, result in\n    if case .success(let response) = result {\n         print(response)\n    }\n}\n```\n\n### Retrieve a distance or duration matrix\n\nSee the travel times or distances between many points using the Matrix API. `Matrix` uses the same access token initialization as `Directions`. Once that is configured, you need to fill  `MatrixOptions` parameters to calculate the desired matrix:\n\n``` swift\nlet matrix = Matrix(credentials: Credentials(accessToken: \"\u003c#your access token#\u003e\")\nlet waypoints = [\n    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.751668, longitude: -122.418408), name: \"Mission Street\"),\n    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.755184, longitude: -122.422959), name: \"22nd Street\"),\n    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.759695, longitude: -122.426911))\n]\nlet matrixOptions = MatrixOptions(sources: waypoints, destinations: waypoints, profileIdentifier: .automobile)\nmatrix.calculate(matrixOptions) { session, result in\n    if case .success(let response) = result,\n       let expectedTravelTime = response.travelTime(from: 0, to: 1) {\n        print(\"Expected route duration from '\\(waypoints[0].name)' to '\\(waypoints[1].name)' is \\(expectedTravelTime / 60) minutes.\")\n    }\n}\n```\n\n## Usage with other Mapbox libraries\n\n### Drawing the route on a map\n\nWith the [Mapbox Maps SDK for iOS](https://docs.mapbox.com/ios/maps/) or [macOS SDK](https://mapbox.github.io/mapbox-gl-native/macos/), you can easily draw the route on a map:\n\n```swift\n// main.swift\n\nif var routeCoordinates = route.shape?.coordinates, routeCoordinates.count \u003e 0 {\n    // Convert the route’s coordinates into a polyline.\n    let routeLine = MGLPolyline(coordinates: \u0026routeCoordinates, count: UInt(routeCoordinates.count))\n\n    // Add the polyline to the map.\n    mapView.addAnnotation(routeLine)\n\n    // Fit the viewport to the polyline.\n    let camera = mapView.cameraThatFitsShape(routeLine, direction: 0, edgePadding: .zero)\n    mapView.setCamera(camera, animated: true)\n}\n```\n\n### Displaying a turn-by-turn navigation interface\n\nThe [Mapbox Navigation SDK for iOS](https://github.com/mapbox/mapbox-navigation-ios/) provides a full-fledged user interface for turn-by-turn navigation along routes supplied by MapboxDirections.\n\n### Drawing Isochrones contours on a map snapshot\n\n[MapboxStatic.swift](https://github.com/mapbox/MapboxStatic.swift) provides an easy way to draw a isochrone contours on a map.\n\n```swift\n// main.swift\nimport MapboxStatic\nimport MapboxDirections\n\nlet centerCoordinate = CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944)\nlet accessToken = \"\u003c#your access token#\u003e\"\n\n// Setup snapshot parameters\nlet camera = SnapshotCamera(\n    lookingAtCenter: centerCoordinate,\n    zoomLevel: 12)\nlet options = SnapshotOptions(\n    styleURL: URL(string: \"\u003c#your mapbox: style URL#\u003e\")!,\n    camera: camera,\n    size: CGSize(width: 200, height: 200))\n\n// Request Isochrone contour to draw on a map\nlet isochrones = Isochrones(credentials: Credentials(accessToken: accessToken))\nisochrones.calculate(IsochroneOptions(centerCoordinate: centerCoordinate,\n                                      contours: .byDistances([.init(value: 500, unit: .meters)]))) { session, result in\n    if case .success(let response) = result {\n        // Serialize the geoJSON\n        let encoder = JSONEncoder()\n        let data = try! encoder.encode(response)\n        let geoJSONString = String(data: data, encoding: .utf8)!\n        let geoJSONOverlay = GeoJSON(objectString: geoJSONString)\n\n        // Feed resulting geoJSON to snapshot options\n        options.overlays.append(geoJSONOverlay)\n\n        let snapshot = Snapshot(\n            options: options,\n            accessToken: accessToken)\n\n        // Display the result!\n        drawImage(snapshot.image)\n    }\n}\n```\n\n## Directions CLI\n\n`MapboxDirectionsCLI` is a command line tool, designed to round-trip an arbitrary, JSON-formatted Directions or Map Matching API response through model objects and back to JSON. This is useful for various scenarios including testing purposes and designing more sophisticated API response processing pipelines. It is supplied as a Swift package.\n\nTo build `MapboxDirectionsCLI` using SPM:\n\n1. `swift build`\n\nTo run (and build if it wasn't yet) `MapboxDirectionsCLI` and see usage:\n\n1. `swift run mapbox-directions-swift -h`\n\nFor further details, see the [MapboxDirectionsCLI documentation](CommandLineTool.md).\n\n## Pricing\n\nAPI calls made to the Directions API are individually billed by request. Review the [pricing information](https://docs.mapbox.com/api/navigation/directions/#directions-api-pricing) and the [pricing page](https://www.mapbox.com/pricing/#directions) for current rates.\n","funding_links":[],"categories":["Swift"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmapbox%2Fmapbox-directions-swift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmapbox%2Fmapbox-directions-swift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmapbox%2Fmapbox-directions-swift/lists"}