Mapbox route еще 2 Аннотации - PullRequest
1 голос

Из API я получаю четыре annotations. В коде я ввожу статический array с местоположениями, например.

Мне нужен маршрут между несколькими annotations, как на следующем скриншоте:

as it should be

Я прочитал следующие уроки:

Аннотации моделей

Добавление нескольких фигур из одного источника фигур

Анимация строки

Мой код:

    class ViewController: UIViewController {

    var mapView: MGLMapView!

    let directions = Directions(accessToken: "my token")

    var coordinates: [CLLocationCoordinate2D] = [
                                                CLLocationCoordinate2D(latitude: 42.97876170515205, longitude: 47.5146782332093),
                                                CLLocationCoordinate2D(latitude: 42.787338526873825, longitude: 47.55432128244579),
                                                CLLocationCoordinate2D(latitude: 42.97164297215167, longitude: 47.50778495604164),
                                                CLLocationCoordinate2D(latitude: 42.14711445441536, longitude: 47.87841796208566)]

    var route: Route?

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView = MGLMapView(frame: view.bounds, styleURL: MGLStyle.lightStyleURL)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.tintColor = .darkGray

        setMapView()
    }

    fileprivate func setMapView() {
        mapView.setUserTrackingMode(.follow, animated: true)
        mapView.styleURL = MGLStyle.lightStyleURL

        mapView.setCenter(CLLocationCoordinate2D(latitude: 42.983060, longitude: 47.504682), zoomLevel: 12, animated: false)
        view.addSubview(mapView)
        mapView.delegate = self

        for (index, coordinate) in coordinates.enumerated() {
            let marker = MGLPointAnnotation()
            marker.coordinate = coordinate
            mapView.addAnnotation(marker)

            //draw line
            if (index + 1) < coordinates.count {
                calculateRoute(from: coordinate, to: coordinates[index + 1]) { (route, error) in
                    if error != nil {
                        print("error getting route")
                    }
                }
            }
        }
    }
}

// нарисовать линию

extension ViewController {
    func calculateRoute(from originCoor: CLLocationCoordinate2D, to destinationCoor: CLLocationCoordinate2D, complition: @escaping (Route?, Error?) -> Void) {

        let origin = Waypoint(coordinate: originCoor, name: "Mapbox")
        let destination = Waypoint(coordinate: destinationCoor, name: "White House")
        let options = NavigationRouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic)

        _ =  directions.calculate(options) { (waypoints, routes, error) in
            guard let route = routes?.first else {print(error.debugDescription); return}
            self.route = route
            self.drawRoute(route: self.route!)

            let coordinateBounds = MGLCoordinateBounds(sw: destinationCoor, ne: originCoor)
            let insets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)
            let routeCam = self.mapView.cameraThatFitsCoordinateBounds(coordinateBounds, edgePadding: insets)
            self.mapView.setCamera(routeCam, animated: true)
        }
    }

    func drawRoute(route: Route) {
        guard route.coordinateCount > 0 else {return}
        let routeCoordinates = route.coordinates!
        let polyline = MGLPolylineFeature(coordinates: routeCoordinates, count: route.coordinateCount)

        if let source = mapView.style?.source(withIdentifier: "route-source") as? MGLShapeSource {
            source.shape = polyline
        } else {
            let source = MGLShapeSource(identifier: "route-source", features: [polyline], options: nil)

            let lineStyle = MGLLineStyleLayer(identifier: "route-style", source: source)

            mapView.style?.addSource(source)
            mapView.style?.addLayer(lineStyle)
        }
    }
}

мой результат:

bad result

Я посмотрел все учебники из Mapbox, и это все, что я получил.

Буду благодарен за любую помощь. Спасибо!

...