Giter Club home page Giter Club logo

maplibre-navigation-ios's Introduction

MapLibre Logo

The Maplibre Navigation SDK for iOS is built on a fork of the Mapbox Navigation SDK v0.21 which is build on top of the Mapbox Directions API (v0.23.0) and contains logic needed to get timed navigation instructions.

With this SDK you can implement turn by turn navigation in your own iOS app while hosting your own Map tiles and Directions API.

Why have we forked

  1. Mapbox decided to put a closed source component to their navigation SDK and introduced a non open source license. Maplibre wants an open source solution.
  2. Mapbox decided to put telemetry in their SDK. We couldn't turn this off without adjusting the source.
  3. We want to use the SDK without paying Mapbox for each MAU and without Mapbox API keys.

All issues are covered with this SDK.

What have we changed

  • Removed EventManager and all its references, this manager collected telemetry data which we don't want to send
  • Transitioned from the Mapbox SDK (version 4.3) to Maplibre Maps SDK (version 5.12.2)
  • Added optional config parameter in NavigationMapView constructor to customize certain properties like route line color

Getting Started

If you are looking to include this inside your project, you have to follow the the following steps:

  1. Install Carthage
    • Open terminal
    • [optional] On M1 Mac change terminal to bash: chsh -s /bin/bash
    • Install Homebrew: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    • Install Carthage: brew install carthage
  2. Create a new XCode project
  3. Create Cartfile
    • Open terminal
    • Change location to root of XCode project: cd path/to/Project
    • Create the Cartfile: touch Cartfile
    • New file will be added: Cartfile
  4. Add Maplibre Maps SPM (Swift Package Manager) depedency by going to your app's project file -> Package Dependencies -> Press the '+' -> https://github.com/maplibre/maplibre-gl-native-distribution -> 'Exact' 5.12.2
  5. Add dependencies to Cartfile
    github "flitsmeister/maplibre-navigation-ios" ~> 1.0.6
    
  6. Build the frameworks
    • Open terminal
    • Change location to root of XCode project: cd path/to/Project
    • Run: carthage bootstrap --platform iOS --use-xcframeworks
    • New files will be added
      • Cartfile.resolved = Indicates which frameworks have been fetched/built
      • Carthage folder = Contains all builded frameworks
  7. Drag frameworks into project: TARGETS -> General -> Frameworks, Libraries..
    • All xcframeworks
  8. Add properties to Info.plist
    • MGLMapboxAccessToken / String / Leave empty = Ensures that the SDK doesn't crash
    • MGLMapboxAPIBaseURL / String / Add url = Url that is being used to GET the navigation JSON
    • NSLocationWhenInUseUsageDescription / String / Add a description = Needed for the location permission
  9. [optional] When app is running on device and you're having problems: Add arm64 to PROJECT -> <Project naam> -> Build Settings -> Excluded Architecture Only
  10. Use the sample code as inspiration

Getting Help

  • Have a bug to report? Open an issue. If possible, include the version of Maplibre Services, a full log, and a project that shows the issue.
  • Have a feature request? Open an issue. Tell us what the feature should do and why you want the feature.

A demo app is currently not available. Please check the Mapbox repository or documentation for examples, especially on the forked version. You can try the provided demo app, which you need to first run carthage update --platform iOS --use-xc-frameworks for in the root of this project.

In order to see the map or calculate a route you need your own Maptile and Direction services.

Use the following code as inspiration:

import Mapbox
import MapboxDirections
import MapboxCoreNavigation
import MapboxNavigation

class ViewController: UIViewController {
    var navigationView: NavigationMapView?
    
    // Keep `RouteController` in memory (class scope),
    // otherwise location updates won't be triggered
    public var mapboxRouteController: RouteController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let navigationView = NavigationMapView(
            frame: .zero,
            // Tile loading can take a while
            styleURL: URL(string: "your style URL here"),
            config: MNConfig())
        self.navigationView = navigationView
        view.addSubview(navigationView)
        navigationView.translatesAutoresizingMaskIntoConstraints = false
        navigationView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        navigationView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        navigationView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        navigationView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        
        let waypoints = [
            CLLocation(latitude: 52.032407, longitude: 5.580310),
            CLLocation(latitude: 51.768686, longitude: 4.6827956)
        ].map { Waypoint(location: $0) }
        
        let options = NavigationRouteOptions(waypoints: waypoints, profileIdentifier: .automobileAvoidingTraffic)
        options.shapeFormat = .polyline6
        options.distanceMeasurementSystem = .metric
        options.attributeOptions = []
        
        print("[\(type(of:self))] Calculating routes with URL: \(Directions.shared.url(forCalculating: options))")
        
        /// URL is based on the base URL in the Info.plist called `MGLMapboxAPIBaseURL`
        /// - Note: Your routing provider could be strict about the user-agent of this app before allowing the call to work
        Directions.shared.calculate(options) { (waypoints, routes, error) in
            guard let route = routes?.first else { return }
            
            let simulatedLocationManager = SimulatedLocationManager(route: route)
            simulatedLocationManager.speedMultiplier = 20
            
            let mapboxRouteController = RouteController(
                along: route,
                directions: Directions.shared,
                locationManager: simulatedLocationManager)
            self.mapboxRouteController = mapboxRouteController
            mapboxRouteController.delegate = self
            mapboxRouteController.resume()
            
            NotificationCenter.default.addObserver(self, selector: #selector(self.didPassVisualInstructionPoint(notification:)), name: .routeControllerDidPassVisualInstructionPoint, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(self.didPassSpokenInstructionPoint(notification:)), name: .routeControllerDidPassSpokenInstructionPoint, object: nil)
            
            navigationView.showRoutes([route], legIndex: 0)
        }
    }
}

// MARK: - RouteControllerDelegate

extension ViewController: RouteControllerDelegate {
    @objc public func routeController(_ routeController: RouteController, didUpdate locations: [CLLocation]) {
        let camera = MGLMapCamera(
            lookingAtCenter: locations.first!.coordinate,
            acrossDistance: 500,
            pitch: 0,
            heading: 0
        )
        
        navigationView?.setCamera(camera, animated: true)
    }
    
    @objc func didPassVisualInstructionPoint(notification: NSNotification) {
        guard let currentVisualInstruction = currentStepProgress(from: notification)?.currentVisualInstruction else { return }
        
        print(String(
            format: "didPassVisualInstructionPoint primary text: %@ and secondary text: %@",
            String(describing: currentVisualInstruction.primaryInstruction.text),
            String(describing: currentVisualInstruction.secondaryInstruction?.text)))
    }
    
    @objc func didPassSpokenInstructionPoint(notification: NSNotification) {
        guard let currentSpokenInstruction = currentStepProgress(from: notification)?.currentSpokenInstruction else { return }
        
        print("didPassSpokenInstructionPoint text: \(currentSpokenInstruction.text)")
    }
    
    private func currentStepProgress(from notification: NSNotification) -> RouteStepProgress? {
        let routeProgress = notification.userInfo?[RouteControllerNotificationUserInfoKey.routeProgressKey] as? RouteProgress
        return routeProgress?.currentLegProgress.currentStepProgress
    }
}

Community

Join the #maplibre-native Slack channel at OSMUS: get an invite at https://slack.openstreetmap.us/ Read the CONTRIBUTING.md guide in order to get familiar with how we do things around here.

License

Code is licensed under MIT and ISC. ISC is meant to be functionally equivalent to the MIT license.

Copyright (c) 2022 MapLibre contributors

maplibre-navigation-ios's People

Contributors

1ec5 avatar akitchen avatar anas10 avatar birkskyum avatar bsudekum avatar captainbarbosa avatar colleenmcginnis avatar davidyou3 avatar dentelezhkin avatar ericdeveloper avatar ericrwolfe avatar frederoni avatar friedbunny avatar gilazr avatar hardsetting avatar joneswah avatar jthramer avatar kasparelmans avatar lloydsheng avatar m-stephen avatar maartenzonneveld avatar manaswinidas avatar marcelhozeman avatar mgurreta avatar milotolboom avatar sealos avatar sjoerdperfors avatar svantulden avatar vincethecoder avatar wwajerowicz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

maplibre-navigation-ios's Issues

Framework built for iOS + iOS Simulator

Navigation SDK version: latest

I installed the sdk as explained in the documentation,

  • I Created the Cartfile
  • Added dependencies to Cartfile
  • Build the frameworks and drag them to my project's framework, libraries

But at the end when I'm trying to build my application, I'm facing with this error

Building for iOS, but the linked and embedded framework 'Mapbox.framework' was built for iOS + iOS Simulator.

To fix it, based targeted device (physical or simulator), I have to execute

lipo -thin arm64 Mapbox.framework/Mapbox -output Mapbox

Can we have a fix to not have to execute any command at the end of the installation and support physical and simulator devices?

Documentation incomplete

Navigation SDK version: latest

It's really hard to understand how to set up the libary in a project: Multiple explanations for the same things, some commands are wrong or do not exist.

Samples don't work.

Would be great to highlight that you have to set the Mapbox key...

Project doesn't compile - Cycle in dependencies between targets

Navigation SDK version: latest

It's not possible to build any of the targets of the project.

Cycle in dependencies between targets 'Example-Objective-C' and 'MapboxCoreNavigation'; building could produce unreliable results. This usually can be resolved by moving the target's Headers build phase before Compile Sources.
Cycle path: Example-Objective-C → MapboxCoreNavigation → Example-Objective-C

Sample-Swift crash randomly

** Navigation SDK version: latest**

Sample-Swift works and then crash randomly, at launch or during usage

Screenshot 2022-08-24 at 12 49 11

Getting started doc not working

It's really hard to understand how to set up the libary in a project: Multiple explanations for the same things, some commands are wrong or do not exist.

Samples don't work.

** Navigation SDK version: latest**

  1. Create new project
  2. Add cartfile
  3. Run carthage update --platform iOS as explained in doc

Error:

Building universal frameworks with common architectures is not possible. The device and simulator slices for "MapboxMobileEvents" both build for: arm64
Rebuild with --use-xcframeworks to create an xcframework bundle instead.

Fix:
3. Run should be carthage update --platform iOS --use-xcframeworks

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.