iOS adds Mapbox map library

Configure credentials

Register and navigate to the Account page. You will need:

  • Public access token:

From the account's tokens page, you can copy the default public token or click the " create a token " button to create a new public token.

  • Secret access token with Downloads:Read scope:

From your account's tokens page, click the " create a token " button.

On the Create Token page, give your token a name and make sure the box next to Downloads:Read scope is checked.

Click the " create token " button at the bottom of the page to create your token.

The token you create is a secret token, which means you will only have one chance to copy it somewhere safe.

Configure secret token

Your secret token allows you to download the SDK directly from Mapbox.

To use your secret token, you need to store it in a .netrc file in your home directory (not the project folder).
Configure 0600 permissions for .netrc:

chmod 0600 ~/.netrc

To set the credentials required to download the SDK, add the following entry to your .netrc file:

machine api.mapbox.com
login mapbox
password YOUR_SECRET_MAPBOX_ACCESS_TOKEN

Configure public token

To configure your public access token, open your project's Info.plist file and add an MBXAccessToken key whose value is your public access token.

Add dependencies

MapBox map library

Mapbox Maps are available through Swift Package Manager (SPM) . To add the Mapbox Maps SDK using SPM you need to configure your environment to download it from Mapbox, make sure you have added the secret token to your .netrc file.

Open your Xcode project and go to File > Swift Packages > Add Package Dependency , enter GitHub - mapbox/mapbox-maps-ios: Interactive, thoroughly customizable maps for iOS powered by vector tiles and Metal as the URL, press Enter to pull in the package , and then click Add Package .

You can use import MapboxMaps to introduce dependency packages in the code.

MapBox navigation library

Mapbox Navigation SDK is available through Swift Package Manager (SPM) . To add the Mapbox Navigation SDK using SPM you need to configure your environment to download it from Mapbox, make sure you have added the secret token to your .netrc file.

Open your Xcode project and go to File > Swift Packages > Add Package Dependency , enter https://github.com/mapbox/mapbox-navigation-ios.git as the URL, press Enter to pull in the package and click Add Package .

Set Dependency Rule to Up to Next Major Version and enter 2.14.0as minimum version

Select the MapboxNavigation library, or MapboxCoreNavigation if you don't need any UI components .

You can use import MapboxNavigation to introduce dependency packages in the code.

Privacy and permissions

Users must grant your app permission before they can access information about their location. Add the following configuration to Info.plist.

Briefly explain to users how the app will use their location data for temporary access:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Your precise location is used to calculate turn-by-turn directions, show your location on the map, and help improve the map.</string>

Add LocationAccuracyAuthorizationDescription as an element of the NSLocationTemporaryUsageDescriptionDictionary dictionary to provide the user with a concise explanation of why the functionality in the application requires its exact location:

<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
  <key>LocationAccuracyAuthorizationDescription</key>
  <string>Please enable precise location. Turn-by-turn directions only work when precise location data is available.</string>
</dict>

Add map

import UIKit
import MapboxMaps

class MapViewController: UIViewController {
    
    internal var mapView: MapView!
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        
        let myResourceOptions = ResourceOptions(accessToken: "your_public_access_token")
        let myMapInitOptions = MapInitOptions(resourceOptions: myResourceOptions)
        mapView = MapView(frame: view.bounds, mapInitOptions: myMapInitOptions)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        self.view.addSubview(mapView)
    }
}

Add a marker to the map

let coordinate = CLLocationCoordinate2DMake(latitude, longitude)

// Initialize a point annotation with a geometry ("coordinate" in this case)
var pointAnnotation = PointAnnotation(coordinate: coordinate)

// Make the annotation show a red pin
pointAnnotation.image = .init(image: UIImage(named: "red_pin")!, name: "red_pin")
pointAnnotation.iconAnchor = .center
pointAnnotation.iconSize = 0.5    //icon image scale

// Create the `PointAnnotationManager` which will be responsible for handling this annotation
let pointAnnotationManager = mapView.annotations.makePointAnnotationManager()

// Add the annotation to the manager in order to render it on the map.
pointAnnotationManager.annotations = [pointAnnotation]

Add route on map

// Define two or more geographic coordinates to connect with a line.
// Line from New York City, NY to Washington, D.C.
let lineCoordinates = [
    CLLocationCoordinate2DMake(40.7128, -74.0060),
    CLLocationCoordinate2DMake(38.9072, -77.0369)
]

// Create the line annotation.
var lineAnnotation = PolylineAnnotation(lineCoordinates: lineCoordinates)
lineAnnotation.lineColor = StyleColor(.blue)

// Create the `PolylineAnnotationManager` which will be responsible for handling this annotation
let lineAnnnotationManager = mapView.annotations.makePolylineAnnotationManager()

// Add the annotation to the manager.
lineAnnnotationManager.annotations = [lineAnnotation]

Set camera position

The camera of the Maps SDK refers to the user's observation point above the map.

The camera's position and behavior are defined by its properties:

  • center: The longitude and latitude the camera is pointing at.
  • bearing: The visual rotation of the map. The bearing value is the compass direction the camera is pointed in to show the user which direction is "up". For example, an orientation of 90° orients the map so that east is facing up.
  • pitch: The visual tilt of the map. A spacing of 0° is perpendicular to the surface, looking straight at the map, while larger values ​​such as 60° are towards the horizon.
  • zoom: The zoom level specifies the distance of the camera from the feature being viewed. At zoom level 0, the viewport shows continents and oceans. The mid-range value of 11 shows city-level detail, and at higher zoom levels the map starts to show buildings and points of interest.
  • padding: An inset for each edge of the map. Affects the rendering centerposition.
  • anchor: The point in the map coordinate system to which the sum should be zoomapplied bearing. and centermutually exclusive.

Set camera on map initialization

// Define center coord, zoom, pitch, bearing
let cameraOptions = CameraOptions(center: CLLocationCoordinate2D(latitude: 40.7135, longitude: -74.0066),
                                          zoom: 15.5,
                                          bearing: -17.6,
                                          pitch: 45)
// Pass camera options to map init options
let options = MapInitOptions(cameraOptions: cameraOptions)
// Pass options when initializing the map 
mapView = MapView(frame: view.bounds, mapInitOptions: options)

Set camera after map initialization

let coordinate = CLLocationCoordinate2DMake(latitude, longitude)
let options = CameraOptions(center: coordinate, zoom: 10)
//不带动画
mapView.mapboxMap.setCamera(to: options)
//带动画
mapView.camera.fly(to: options, duration: 3)

Set camera based on device location

if let locationCoordinate = self.mapView?.location.latestLocation?.coordinate {
  mapView.mapboxMap.setCamera(to: CameraOptions(center: locationCoordinate, zoom: 15))
}

Get road speed limit

import MapboxCoreNavigation
import MapboxNavigation

class LocationManager {
    private let passiveLocationManager = PassiveLocationManager()
    private lazy var passiveLocationProvider = PassiveLocationProvider(locationManager: passiveLocationManager)

    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(didUpdatePassiveLocation), name: Notification.Name.passiveLocationManagerDidUpdate, object: nil)
        passiveLocationProvider.startUpdatingLocation()
    }

    @objc func didUpdatePassiveLocation(_ notification: Notification) {
        let speedLimitObj = notification.userInfo?[PassiveLocationManager.NotificationUserInfoKey.speedLimitKey]
        if (speedLimitObj != nil) {
            let speedLimit: Measurement<UnitSpeed> = speedLimitObj! as! Measurement<UnitSpeed>
            print("speedLimit:", speedLimit, speedLimit.value)
        }
    }
}

Guess you like

Origin blog.csdn.net/watson2017/article/details/132966800