在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):mapbox/mapbox-directions-swift开源软件地址(OpenSource Url):https://github.com/mapbox/mapbox-directions-swift开源编程语言(OpenSource Language):Swift 98.4%开源软件介绍(OpenSource Introduction):Mapbox Directions for SwiftMapbox 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 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 startedSpecify the following dependency in your Carthage Cartfile:
Or in your CocoaPods Podfile: # Latest stable release
pod 'MapboxDirections', '~> 2.6'
# Latest prerelease
pod 'MapboxDirections', :git => 'https://github.com/mapbox/mapbox-directions-swift.git', :tag => 'v2.6.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: "2.6.0")
// Latest prerelease
.package(name: "MapboxDirections", url: "https://github.com/mapbox/mapbox-directions-swift.git", .exact("2.6.0-rc.1")) Then 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
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. UsageYou’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 The examples below are each provided in Swift (denoted with Calculating directions between locationsThe main directions class is // main.swift
import MapboxDirections
let directions = Directions(credentials: Credentials(accessToken: "<#your access token#>")) Alternatively, you can place your access token in the // main.swift
let directions = Directions.shared With the directions object in hand, construct a RouteOptions object and pass it into the // 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 networkIf 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 Build an isochrone mapTell the user how far they can travel within certain distances or times of a given location using the Isochrone API. let isochrones = Isochrones(credentials: Credentials(accessToken: "<#your access token#>"))
let isochroneOptions = IsochroneOptions(centerCoordinate: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944),
contours: .byDistances([
.init(value: 500, unit: .meters, color: .orange),
.init(value: 1, unit: .kilometers, color: .red)
]))
isochrones.calculate(isochroneOptions) { session, result in
if case .success(let response) = result {
print(response)
}
} ... Usage with other Mapbox librariesDrawing the route on a mapWith 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 interfaceThe Mapbox Navigation SDK for iOS provides a full-fledged user interface for turn-by-turn navigation along routes supplied by MapboxDirections. Drawing Isochrones contours on a map snapshotMapboxStatic.swift provides an easy way to draw a isochrone contours on a map. // main.swift
import MapboxStatic
import MapboxDirections
let centerCoordinate = CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944)
let accessToken = "<#your access token#>"
// Setup snapshot parameters
let camera = SnapshotCamera(
lookingAtCenter: centerCoordinate,
zoomLevel: 12)
let options = SnapshotOptions(
styleURL: URL(string: "<#your mapbox: style URL#>")!,
camera: camera,
size: CGSize(width: 200, height: 200))
// Request Isochrone contour to draw on a map
let isochrones = Isochrones(credentials: Credentials(accessToken: accessToken))
isochrones.calculate(IsochroneOptions(centerCoordinate: centerCoordinate,
contours: .byDistances([.init(value: 500, unit: .meters)]))) { session, result in
if case .success(let response) = result {
// Serialize the geoJSON
let encoder = JSONEncoder()
let data = try! encoder.encode(response)
let geoJSONString = String(data: data, encoding: .utf8)!
let geoJSONOverlay = GeoJSON(objectString: geoJSONString)
// Feed resulting geoJSON to snapshot options
options.overlays.append(geoJSONOverlay)
let snapshot = Snapshot(
options: options,
accessToken: accessToken)
// Display the result!
drawImage(snapshot.image)
}
} Directions CLI
To build
To run (and build if it wasn't yet)
For further details, see the MapboxDirectionsCLI documentation. PricingAPI calls made to the Directions API are individually billed by request. Review the pricing information and the pricing page for current rates. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论