Coder Social home page Coder Social logo

mapbox / mapbox-directions-swift Goto Github PK

View Code? Open in Web Editor NEW
181.0 118.0 88.0 68.39 MB

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

Home Page: https://www.mapbox.com/navigation/

License: ISC License

Swift 98.16% Ruby 0.76% Objective-C 0.04% Shell 0.76% C 0.01% Python 0.27%
directions osrm swift ios macos tvos watchos openstreetmap traffic routing

mapbox-directions-swift's Introduction

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" ~> 2.14
# Latest prerelease
github "mapbox/mapbox-directions-swift" "v2.11.0-alpha.1"

Or in your CocoaPods Podfile:

# Latest stable release
pod 'MapboxDirections', '~> 2.14'
# Latest prerelease
pod 'MapboxDirections', :git => 'https://github.com/mapbox/mapbox-directions-swift.git', :tag => 'v2.11.0-alpha.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.14.0")
// Latest prerelease
.package(name: "MapboxDirections", url: "https://github.com/mapbox/mapbox-directions-swift.git", .exact("2.11.0-alpha.1"))

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 1.10 or above
    • Carthage 0.38 or above
    • Swift Package Manager 5.5 or above
  • Xcode 13 or above
  • One of the following operating systems:
    • iOS 12.0 or above
    • macOS 10.14 or above
    • tvOS 12.0 or above
    • watchOS 5.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 MBXAccessToken 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 documentation available by the link in the releases.

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: Credentials(accessToken: "<#your access token#>"))

Alternatively, you can place your access token in the MBXAccessToken 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.

Build an isochrone map

Tell 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:

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)
    }
}

Retrieve a distance or duration matrix

See 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:

let matrix = Matrix(credentials: Credentials(accessToken: "<#your access token#>")
let waypoints = [
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.751668, longitude: -122.418408), name: "Mission Street"),
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.755184, longitude: -122.422959), name: "22nd Street"),
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.759695, longitude: -122.426911))
]
let matrixOptions = MatrixOptions(sources: waypoints, destinations: waypoints, profileIdentifier: .automobile)
matrix.calculate(matrixOptions) { session, result in
    if case .success(let response) = result,
       let expectedTravelTime = response.travelTime(from: 0, to: 1) {
        print("Expected route duration from '\(waypoints[0].name)' to '\(waypoints[1].name)' is \(expectedTravelTime / 60) minutes.")
    }
}

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.

Drawing Isochrones contours on a map snapshot

MapboxStatic.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

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.

To build MapboxDirectionsCLI using SPM:

  1. swift build

To run (and build if it wasn't yet) MapboxDirectionsCLI and see usage:

  1. swift run mapbox-directions-swift -h

For further details, see the MapboxDirectionsCLI documentation.

Pricing

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

mapbox-directions-swift's People

Contributors

1ec5 avatar aataraxiaa avatar akitchen avatar avi-c avatar azarovalex avatar bamx23 avatar chezzdev avatar danswick avatar dependabot[bot] avatar ericrwolfe avatar fabian-guerra avatar frederoni avatar freenerd avatar friedbunny avatar heystenson avatar incanus avatar jill-cardamon avatar jthramer avatar kried avatar m-stephen avatar mapbox-github-ci-writer-public-1[bot] avatar maximalien avatar s2ler avatar sebastianosinski avatar sevazhukov avatar shanma1991 avatar simonseyer avatar udumft avatar vincethecoder avatar zorgiepoo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mapbox-directions-swift's Issues

Support for Optimization API

This is a placeholder for a variant of Directions API v5 that we’ll want to support in MapboxDirections.swift soon.

Directions returned are nil

Hello, I am using the code you have supplied in your README example. When I debug the code, "waypoints" is nil, "error" is nil, "routes" are nil,

Its the exact same code

Serialize ref field

Once Project-OSRM/osrm-backend#2857 makes it into production and the Directions API exposes a separate ref field for each step, we'll need to add a route reference property to each RouteStep, similar to the one for destinations. Assuming that v4 doesn't add this separate field, we'll fall back to a regular expression that parses the ref out of the way name.

Better yet, we could implement a Road struct that bundles a road's name with its route designation. Eventually that struct could grow to include other information about the road, such as its classification.

/cc @bsudekum

Switch to Alamofire for requests

It's not possible to cleanly set a user agent header with RequestKit, and there are likely other methods that we'll need down the line, so let's switch to the battle-tested Alamofire.

Routes are not working properly

I was testing direction API, tried to get direction for two coordinates (45.52258, -122.6732) & (45.62258, -122.6732)
The polyline which is getting drawn is totally wrong. It is not using road path.
Please someone help me if there are any mistakes. Otherwise I have to try other libraries

- (void)addTestRoute
{
NSArray<JobLocation *> *array = [LocationsManager getJobLocations];
NSArray<MBWaypoint *> *waypoints = @[[[MBWaypoint alloc] initWithCoordinate:CLLocationCoordinate2DMake(45.52258, -122.6732) coordinateAccuracy:-1 name:@"Mapbox"], [[MBWaypoint alloc] initWithCoordinate:CLLocationCoordinate2DMake(45.62258, -122.6732) coordinateAccuracy:-1 name:@"Mapbox"]];

MBRouteOptions *options = [[MBRouteOptions alloc] initWithWaypoints:waypoints
                                                  profileIdentifier:@"mapbox/driving"];
options.includesSteps = YES;

MBDirections *directions = [MBDirections sharedDirections];

NSURLSessionDataTask *task = [directions calculateDirectionsWithOptions:options completionHandler:^(NSArray<MBWaypoint *> * _Nullable waypoints, NSArray<MBRoute *> * _Nullable routes, NSError * _Nullable error) {
    if (error) {
        NSLog(@"Error calculating directions: %@", error);
        return;
    }
    
    MBRoute *route = routes.firstObject;
    MBRouteLeg *leg = route.legs.firstObject;
    if (leg) {
        NSLog(@"Route via %@:", leg);
        
        NSLengthFormatter *distanceFormatter = [[NSLengthFormatter alloc] init];
        NSString *formattedDistance = [distanceFormatter stringFromMeters:leg.distance];
        
        NSDateComponentsFormatter *travelTimeFormatter = [[NSDateComponentsFormatter alloc] init];
        travelTimeFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyleShort;
        NSString *formattedTravelTime = [travelTimeFormatter stringFromTimeInterval:route.expectedTravelTime];
        
        NSLog(@"Distance: %@; ETA: %@", formattedDistance, formattedTravelTime);
        
        for (MBRouteStep *step in leg.steps) {
            NSLog(@"%@", step.instructions);
            NSString *formattedDistance = [distanceFormatter stringFromMeters:step.distance];
            NSLog(@"— %@ —", formattedDistance);
        }
    }
    
    if (route.coordinateCount) {
        // Convert the route’s coordinates into a polyline.
        CLLocationCoordinate2D *routeCoordinates = malloc(route.coordinateCount * sizeof(CLLocationCoordinate2D));
        [route getCoordinates:routeCoordinates];
        MGLPolyline *routeLine = [MGLPolyline polylineWithCoordinates:routeCoordinates count:route.coordinateCount];
        
        // Add the polyline to the map and fit the viewport to the polyline.
        [self.mapView addAnnotation:routeLine];
        [self.mapView setVisibleCoordinates:routeCoordinates count:route.coordinateCount edgePadding:UIEdgeInsetsZero animated:YES];
        
        // Make sure to free this array to avoid leaking memory.
        free(routeCoordinates);
    }
}];
}

calculateDirectionsWithCompletionHandler not running

Hey there,

Apologies if this "issue" is in the wrong area. If it is, let me know and I will remove it.

When running directions.calculateDirectionsWithCompletionHandler { (response, error) in ...... } and adding a breakpoint to the first line inside the completion handler, the code seems to never be executed. It never hits the breakpoint, meaning nothing inside the completion handler gets executed. Can anyone think of possibly why?
I've set the MBDirectionsRequest and MBDirectionsRequest correctly as far as I can tell.

Here's the full method:

func calculateTravelInfoMB() {
        let request = MBDirectionsRequest(sourceCoordinate: start_location, destinationCoordinate: stop_location)
        let directions = MBDirections(request: request, accessToken: "pk.xxxxxxxxxxx") //removed for security I suppose
        directions.calculateDirectionsWithCompletionHandler { (response, error) in
            if error != nil {
                NSNotificationCenter.defaultCenter().postNotificationName("tripInfoUnavailable-\(self.name)", object: nil)
                global.showAlert("Hmm...", message: "Something went wrong while trying to get travel information for the route \(self.name). \n\n\(error!.localizedDescription)")
                println("Error getting directions - \(error)")
            } else {
                self.travelInfoMB = response
                NSNotificationCenter.defaultCenter().postNotificationName("tripDataChanged-\(self.name)", object: nil)
            }
        }
    }

Expose step weights

RouteStep should have a property that indicates the weight the step was given for the current profile. (Currently the only supported weight metric is “routability”, but “duration” and “distance” could also be possible in the future.)

The JSON response puts this information in a weight property, but I think we should either qualify that word (routingWeight?) or choose a less overloaded word (relevance?).

Add RouteShapeFormat for polyline with precision 6

For completeness’ sake, the RouteShapeFormat enumeration should have a polyline6 case for Polyline encoding with the usual 1×10⁶ precision, to match the geometries=polyline6 option supported by Directions API v5 (but not v4).

Use-lane, rotary maneuver types

ManeuverType should have useLane and traverseRotary values that correspond to the Directions API’s use lane and rotary types, respectively. We should also update the documentation for RouteStep.exitIndex to indicate that it applies to rotaries as well as roundabouts.

/cc @bsudekum @mayagao

RouteStep’s maneuverType, maneuverDirection, transportType properties don’t bridge to Objective-C

RouteStep’s maneuverType, maneuverDirection, and transportType properties don’t bridge to Objective-C, because it isn’t possible for an enumeration-typed value to be nullable in Objective-C. Instead of making these properties optional, we’d need to add .none cases to the ManeuverType, ManeuverDirection, and TransportType enumerations. The tradeoff is that Swift developers would be unable to use optional chaining syntax with these properties; instead, they’d have to explicitly check for .none. (Yuck!)

/cc @bsudekum @cammace

Replace CocoaPods with Carthage for example application

We currently rely on CocoaPods to manage dependencies for both building the framework locally and vending the framework to downstream CocoaPods users. We should replace the former usage with Carthage (or Swift Package Manager, perhaps) so that it’s easier to contribute to the project.

/cc @tmcw @boundsj

Swift3 Branch - Carthage error

On Swift3 branch using Cartfile

github "raphaelmor/Polyline" ~> 4.0.0
github "Mapbox/MapboxDirections.swift" "swift3"

carthage update --platform iOS

gives error:

The sandbox is not in sync with the Podfile.lock

Crash getting v4 walking directions

A new v4 based on OSRMv5 was deployed, causing a crash for walking directions:

Exception Type:  SIGTRAP
Exception Codes: #0 at 0x1011aa940
Crashed Thread:  0

Thread 0 Crashed:
0   MapboxDirections                     0x00000001011aa940 _TTSf4g_gs_n_n___TFC16MapboxDirections11MBRouteStepcfT4jsonGVs10DictionarySSPs9AnyObject__17profileIdentifierSS7versionOCS_19MBDirectionsRequest10APIVersion_S0_ (MBDirectionsResponse.swift:196)
1   MapboxDirections                     0x00000001011aab80 _TTSf4g_g_g_gs_n_n___TFC16MapboxDirections10MBRouteLegcfT6sourceCS_7MBPoint11destinationS1_4jsonGVs10DictionarySSPs9AnyObject__17profileIdentifierSS7versionOCS_19MBDirectionsRequest10APIVersion_S0_ (MBDirectionsResponse.swift:0)
2   MapboxDirections                     0x00000001011ab21c _TTSf4g_g_g_g_gs_n_n___TFC16MapboxDirections7MBRoutecfT6sourceCS_7MBPoint9waypointsGSaS1__11destinationS1_4jsonGVs10DictionarySSPs9AnyObject__17profileIdentifierSS7versionOCS_19MBDirectionsRequest10APIVersion_S0_ (MBDirectionsResponse.swift:0)
3   MapboxDirections                     0x00000001011a74d8 _TFC16MapboxDirections7MBRouteCfT6sourceCS_7MBPoint9waypointsGSaS1__11destinationS1_4jsonGVs10DictionarySSPs9AnyObject__17profileIdentifierSS7versionOCS_19MBDirectionsRequest10APIVersion_S0_ (MBDirectionsResponse.swift:0)
4   MapboxDirections                     0x000000010119f2d4 _TFFC16MapboxDirections12MBDirections40calculateDirectionsWithCompletionHandlerFFTGSqCS_20MBDirectionsResponse_GSqCSo7NSError__T_T_U_FTCS_7MBPointGSaS3__S3_GSaGVs10DictionarySSPs9AnyObject___GSqS2___T_ (MBDirections.swift:76)
5   MapboxDirections                     0x000000010119e6bc _TPA__TFFC16MapboxDirections12MBDirections40calculateDirectionsWithCompletionHandlerFFTGSqCS_20MBDirectionsResponse_GSqCSo7NSError__T_T_U_FTCS_7MBPointGSaS3__S3_GSaGVs10DictionarySSPs9AnyObject___GSqS2___T_ (MBDirections.swift:0)
6   MapboxDirections                     0x00000001011a1af8 _TTSf2n_n_i_n_n_n___TFFFC16MapboxDirections12MBDirectionsP33_9AB848AFC329A49F8F01862214F64FC214taskWithRouterFTOS_18MBDirectionsRouter17completionHandlerFTCS_7MBPointGSaS2__S2_GSaGVs10DictionarySSPs9AnyObject___GSqCSo7NSError__T_12errorHandlerFGSqS5__T__GSqCSo20NSURLSessionDataTask_U_FTGSqGS3_SSPS4____GSqPs9ErrorType___T_U5_FT_T_ (MBDirections.swift:199)
7   MapboxDirections                     0x000000010119ef74 _TPA__TTSf2n_n_i_n_n_n___TFFFC16MapboxDirections12MBDirectionsP33_9AB848AFC329A49F8F01862214F64FC214taskWithRouterFTOS_18MBDirectionsRouter17completionHandlerFTCS_7MBPointGSaS2__S2_GSaGVs10DictionarySSPs9AnyObject___GSqCSo7NSError__T_12errorHandlerFGSqS5__T__GSqCSo20NSURLSessionDataTask_U_FTGSqGS3_SSPS4____GSqPs9ErrorType___T_U5_FT_T_ (MBDirections.swift:0)

/cc @mapbox/directions @bleege @zugaldia

Swift 3 Migration

Hi guys,

I use MapboxDirections in my app (https://itunes.apple.com/ie/app/bikey/id1048962300?mt=8).
I am migrating my app to Swift 3 in preparation for it's GA release and was wondering what the plans are with MapboxDirections.swift.

Do you guys have plans to get a Swift 3 branch up and running?

I would also love to contribute, so if you guys don't have plans to do this right now, I could definitely help out with this.

Best,
Pete

Test v4 API

RouteOptionsV4 and associated classes represent a mostly parallel code path with a slightly different set of edge cases. We need tests for this code path.

/cc @tmcw

Swift 3 Migration - Polyline Errors

I am attempting to migrate to swift 3. In my pod file I am using:

pod 'MapboxDirections.swift', :git => 'https://github.com/mapbox/MapboxDirections.swift.git', :tag => 'v0.6.0', :branch => 'swift3'

After pod install, pod udpdate, and convert to swift 3, I am recieving 4 errors in Polyline.swift.

Did I miss anything in the migration? I saw discussion about polyline in other issues like (#61 (comment)) but wasn't sure what I needed to do differently.

Any help would be appreciated. Thanks!

Serialize pronunciation field

The Road class or struct we’re planning to add for #67 needs a pronunciation property, of type String?, that corresponds to the field of the same name in the Directions API response.

/cc @bsudekum

Add new ref key

Example response:

{
    mode: "driving",
    duration: 597,
    maneuver: {
        bearing_after: 94,
        type: "new name",
        modifier: "straight",
        bearing_before: 98,
        location: [
            -122.289247,
            37.826344
        ],
        instruction: "Continue straight onto MacArthur Freeway (I 580)"
    },
    ref: "I 580",
    distance: 15717.4,
    name: "MacArthur Freeway (I 580)"
}

From osrm-backend changelog:

new ref field in the RouteStep object. It contains the reference code or name of a way. Previously merged into the name property like name (ref) and are now separate fields.

/cc @1ec5

create framework

We should create a MapboxDirections.framework that can be used by Objective-C apps as well.

Persist original JSON response

An application may want to add its own request/response logging functionality. Currently, if it uses the built-in URL request functionality, it has to transform Route objects and so forth into a string-convertible format. We should add the original serialized JSON to the completion handler just in case the application needs it.

/cc @willwhite

Add support for route leg annotations

The RouteLeg and RouteStep classes should have properties or perhaps methods that provide “annotation” information (distance, duration, or speed) between pairs of coordinates along the leg or step.

From the Directions API v5 documentation for the RouteLeg object:

annotations: An annotations object that contains additional details about each line segment along the route geometry. Each entry in an annotations field corresponds to a coordinate along the route geometry.

We should come up with a name other than “annotation” for this property, because that term is very well understood to mean what other platforms call “map markers”. In particular, the Mapbox iOS and macOS SDKs have full-fledged annotation APIs that have nothing to do with this feature. (In those SDKs, one kind of annotation is a polyline annotation.)

/cc @bsudekum @freenerd

Error: module 'MapboxDirections' not found

Hi,

I am using xcode 8.2.1 and Objective-C.
Installed library MapboxDirections using Cocoapods. I tried installing in two variations.
From option 1 I'm getting error as **module 'MapboxDirections' not found **

I am importing it as @import MapboxDirections;

pod file example 1:

platform :ios, '8.0'
use_frameworks!

target 'My first GL app' do
pod 'Mapbox-iOS-SDK', '~> 3.3.7'
pod 'MapboxDirections.swift', :git => 'https://github.com/mapbox/MapboxDirections.swift.git', :tag => 'v0.6.0'
end

pod file example 2:

platform :ios, '8.0'
use_frameworks!

target 'My first GL app' do
pod 'Mapbox-iOS-SDK', '~> 3.3.7'
pod 'MapboxDirections.swift', :git => 'https://github.com/mapbox/MapboxDirections.swift.git', :branch => 'swift3'
end

When I tried option 2, I'm getting could not build module 'MapboxDirections'

Support Carthage

v0.5.0 does not support installation via Carthage. Here are the results when Carthage tries to build MapboxDirections.swift:

$ carthage update
*** Fetching MapboxDirections.swift
*** Downloading MapboxDirections.swift.framework binary at "v0.5.0"
*** Checking out MapboxDirections.swift at "v0.5.0"
*** xcodebuild output can be found in /var/folders/s5/2p4466vn2cv5mslx9ydthw6m0000gn/T/carthage-xcodebuild.aYLxWu.log
*** Building scheme "MapboxDirections" in MapboxDirections.xcodeproj
** BUILD FAILED **

The following build commands failed:
    PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/jason/Library/Developer/Xcode/DerivedData/MapboxDirections-awevmnvtblxkbgdzugqxbaoxvrlk/Build/Intermediates/MapboxDirections.build/Release-iphoneos/MapboxDirections.build/Script-E4F58AFE16C929A75F6A3D5E.sh
(1 failure)
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
A shell task (/usr/bin/xcrun xcodebuild -project /Users/jason/Desktop/Carthage/Carthage/Checkouts/MapboxDirections.swift/MapboxDirections.xcodeproj -scheme MapboxDirections -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
** BUILD FAILED **

The following build commands failed:
    PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/jason/Library/Developer/Xcode/DerivedData/MapboxDirections-awevmnvtblxkbgdzugqxbaoxvrlk/Build/Intermediates/MapboxDirections.build/Release-iphoneos/MapboxDirections.build/Script-E4F58AFE16C929A75F6A3D5E.sh
(1 failure)

Cartfile:

github "Mapbox/MapboxDirections.swift"

/cc @1ec5

v5 route geometry uses incorrect precision

The v5 API uses a different precision with polyline-encoded geometry than the v4 API does. We’re decoding the geometry correctly for v4, but geometries decoded from v5 responses have the wrong scale, causing the route line to wind up in the Atlantic Ocean around Null Island.

/ref #27
/cc @tmcw

How to identify returned waypoints with the ones that were passed into RouteOptions?

I'm looking for a way to identify the returned waypoints with the ones that were passed into the RouteOptions.

let options = RouteOptions(waypoints: waypoints, profileIdentifier: MBDirectionsProfileIdentifier.cycling)
options.includesSteps = true

task = directions.calculate(options) { [unowned self] (waypoints, routes, error) in

}

I first tried to set a name for each Waypoint, but the names of the returned waypoints are different to the ones set.

Other options are:

  • If the count of the passed in waypoints is exactly the same as the ones returned from the service, I can map them by their indices. Is this the case?
  • If the first options is answered with no, then I could compare the coordinates of the returned waypoints with the ones passed into the RouteOptions, but I don't think that would be performant and comparing floating numbers is always a problem.
  • Any other ideas?

What is the recommended solution for this use case?

Built-in support for OSRM

This library should offer built-in support for talking to an OSRM server directly. Similar to the existing support for Directions API v4, an OSRMRouteOptions class would inherit from RouteOptions, and we'd have subclasses of Route, RouteLeg, and RouteStep that perform any necessary translation of the JSON data into the Directions API format.

/ref mapbox/mapbox-navigation-ios#46
/cc @danpat

migrate to Swift 2.0

@harlanhaskins took a stab at this in #7, which also per #6 gets rid of SwiftyJSON, which I think is ok.

We should review that PR and/or otherwise migrate to Swift 2.0.

Add test cases for failures

We should have test cases covering

  • HTTP failure, like a 500 with gibberish content
  • Request failure, like a 403 with a JSON message property

taskWithRouter causes errors

When attempting to incorporate the Directions files into my application, the error

Cannot convert call result type '()' to expected type 'NSURLSessionDataTask?'

caused by

`return router.loadJSON(JSON.self) { [weak self] (json, error) in``... in MBDirections.swift

halts compilation of the application when using the example code. I've built the example app provided and ran the tests, which all pass.

sample code for routeCoordinates not working

Under the section "Drawing the route on a map" the following snippet is listed:

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

    // Add the polyline to the map and fit the viewport to the polyline.
    mapView.addAnnotation(routeLine)
    mapView.setVisibleCoordinates(routeCoordinates, count: route.coordinateCount, edgePadding:                 UIEdgeInsetsZero, animated: true)
}

the var routeCoordinates is an array with CLLocationCoordinate2D objects, however the method setVisibleCoordinates() first parameter is just CLLocationCoordinate2D.

I am not sure if i should be iterating through and updating the visible coordinates based on each one in the array, however, even when i try to just say like the first object of the array it still gives me an error which seems to be related to objC. It says it wants mutablePointer CLLocationCoordinate2D, and i'm not sure what to do there.

Is this code wrong or am I missing something?

add to HipChat

Can someone in @mapbox/devops please add notifications to HipChat #mobile?

Serialize intersections field

A RouteStep object in the response data now includes an intersections field that indicates the location and configuration of each intermediate intersection along the way between two maneuvers. The application can use this information to tighten up rerouting logic around known intersections. Currently the library drops this data, but it should be preserved in some object-oriented form.

/cc @willwhite @zugaldia

Swift example app fails to run because of WatchKit

This failure occurs when you try to run the current master branch in Xcode 8 on the simulator:

WatchKit 2 app contains a framework at /Library/Developer/CoreSimulator/Devices/.../Directions (Swift).app/Watch/WatchExample.app/Frameworks/MapboxDirections.framework. Frameworks are only allowed at that location in WatchKit apps compatible with watchOS 3.0 or later.

/cc @1ec5

MBDirections init return nil

v0.6.0

NSString token = @"pk.eyJ1IjoidG9ueWlvcyIsImEiOiJjaXU4MHo2dzYwMDFyMnlueHpkdTFtODZzIn0.o4m3pnlfCqUKGVCX-9_O***";
MBDirections *directions = [[MBDirections alloc] initWithAccessToken:token];

who can help me why the directions is return nil

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.