All Projects → mapbox → Mapbox Directions Swift

mapbox / Mapbox Directions Swift

Licence: isc
Traffic-aware directions and map matching in Swift on iOS, macOS, tvOS, watchOS, and Linux

Programming Languages

swift
15916 projects

Projects that are alternatives of or similar to Mapbox Directions Swift

organicmaps
🍃 Organic Maps is a free Android & iOS offline maps app for travelers, tourists, hikers, and cyclists. It uses crowd-sourced OpenStreetMap data and is developed with love by MapsWithMe (MapsMe) founders and our community. No ads, no tracking, no data collection, no crapware. Your donations and positive reviews motivate and inspire our small team!
Stars: ✭ 3,689 (+3107.83%)
Mutual labels:  navigation, openstreetmap, routing
Mapboxstatic.swift
Static map snapshots with overlays in Swift or Objective-C on iOS, macOS, tvOS, and watchOS
Stars: ✭ 162 (+40.87%)
Mutual labels:  tvos, watchos, openstreetmap
Predicateflow
Write amazing, strong-typed and easy-to-read NSPredicate.
Stars: ✭ 98 (-14.78%)
Mutual labels:  tvos, watchos
Prex
🔁Unidirectional data flow architecture with MVP and Flux combination for Swift
Stars: ✭ 102 (-11.3%)
Mutual labels:  tvos, watchos
Ios Samples
Xamarin.iOS sample apps
Stars: ✭ 1,501 (+1205.22%)
Mutual labels:  tvos, watchos
Swiftyattributes
A Swifty API for attributed strings
Stars: ✭ 1,303 (+1033.04%)
Mutual labels:  tvos, watchos
Mixpanel
Unofficial Swift Mixpanel client
Stars: ✭ 93 (-19.13%)
Mutual labels:  tvos, watchos
Awesome Rubymotion
A collection of awesome RubyMotion example apps, libraries, tools, frameworks, software and resources
Stars: ✭ 103 (-10.43%)
Mutual labels:  tvos, watchos
Host.swift
*Host.swift is no longer maintained*, please use Hostess.swift: https://github.com/rjstelling/Hostess.swift. A Swift implementation of NSHost that works on iOS, OS X and tvOS. Host.swift is safe to use in a framework because it does not require a bridging header.
Stars: ✭ 83 (-27.83%)
Mutual labels:  tvos, watchos
Sniffer
Networking activity logger for Swift
Stars: ✭ 108 (-6.09%)
Mutual labels:  tvos, watchos
Swifterswift
A handy collection of more than 500 native Swift extensions to boost your productivity.
Stars: ✭ 10,706 (+9209.57%)
Mutual labels:  tvos, watchos
Conbini
Publishers, operators, and subscribers to supplement Combine.
Stars: ✭ 109 (-5.22%)
Mutual labels:  tvos, watchos
Extendable
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.
Stars: ✭ 88 (-23.48%)
Mutual labels:  tvos, watchos
Activityrings
An attempt to recreate the ring controls in Apple’s Activity app
Stars: ✭ 88 (-23.48%)
Mutual labels:  tvos, watchos
Egocache
Fast Caching for Objective-C (iPhone & Mac Compatible)
Stars: ✭ 1,339 (+1064.35%)
Mutual labels:  tvos, watchos
Commoncrypto
CommonCrypto Swift module
Stars: ✭ 87 (-24.35%)
Mutual labels:  tvos, watchos
Sdwebimagewebpcoder
A WebP coder plugin for SDWebImage, use libwebp
Stars: ✭ 101 (-12.17%)
Mutual labels:  tvos, watchos
Diff
Simple diff library in pure Swift
Stars: ✭ 110 (-4.35%)
Mutual labels:  tvos, watchos
Mothership
iTunes Connect Library inspired by FastLane
Stars: ✭ 72 (-37.39%)
Mutual labels:  tvos, watchos
Swiftlinkpreview
It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.
Stars: ✭ 1,216 (+957.39%)
Mutual labels:  tvos, watchos

Mapbox Directions for Swift

CircleCI Carthage compatible CocoaPods SPM compatible codecov

Mapbox Directions for Swift (formerly MapboxDirections.swift) makes it easy to connect your iOS, macOS, tvOS, watchOS, or Linux 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" ~> 1.2
# Latest prerelease
github "mapbox/mapbox-directions-swift" "v1.2.0-rc.1"

Or in your CocoaPods Podfile:

# Latest stable release
pod 'MapboxDirections', '~> 1.2'
# Latest prerelease
pod 'MapboxDirections', :git => 'https://github.com/mapbox/mapbox-directions-swift.git', :tag => 'v1.2.0-rc.1'

Or in your Swift Package Manager Package.swift:

// Latest stable release
.package(name: "MapboxDirections", url: "https://github.com/mapbox/mapbox-directions-swift.git", from: "1.2.0")
// Latest prerelease
.package(name: "MapboxDirections", url: "https://github.com/mapbox/mapbox-directions-swift.git", from: "1.2.0")

Then import MapboxDirections.

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.

System requirements

  • One of the following package managers:
    • CocoaPods (CocoaPods 1.10 or above if using Xcode 12)
    • Carthage 0.19 or above (run this script instead of carthage if using Xcode 12)
    • Swift Package Manager 5.3 or above
  • Xcode 11 or above (Xcode 12 or above if using Swift Package Manager)
  • One of the following operating systems:
    • iOS 10.0 or above
    • macOS 10.12.0 or above
    • tvOS 10.0 or above
    • watchOS 3.0 or above
    • Any Linux distribution supported by Swift

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.

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(credentials: DirectionsCredentials(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) { (session, result) in
    switch result {
    case .failure(let error):
        print("Error calculating directions: \(error)")
    case .success(let response):
        guard let route = response.routes?.first, let leg = route.legs.first else {
            return
        }
        
        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.

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) { (session, result) in
    switch result {
    case .failure(let error):
        print("Error matching coordinates: \(error)")
    case .success(let response):
        guard let match = response.matches?.first, let leg = match.legs.first else {
            return
        }
        
        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

The Mapbox Navigation SDK for iOS provides a full-fledged user interface for turn-by-turn navigation along routes supplied by MapboxDirections.

Directions CLI

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 also supplied as a Swift package.

To build MapboxDirectionsCLI using Carthage pipeline:

  1. carthage build --platform macos
  2. open MapboxDirections.xcodeproj
  3. Select MapboxDirectionsCLI target.

To build MapboxDirectionsCLI using SPM:

  1. swift build
  2. swift run MapboxDirectionsCLI -h to see usage.

Pricing

API calls made to the Directions API are individually billed by request. Review the pricing information and the pricing page for current rates.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].