【问题标题】:MapBox iOS: How to access a routes coordinates to draw it using polylineMapBox iOS:如何访问路线坐标以使用折线绘制它
【发布时间】:2021-07-27 10:09:01
【问题描述】:

我在计算后尝试在 Mapbox 中使用 MGLPolylineFeature 显示路线。计算有效,我的地图调整到正确的点,我似乎无法显示折线,因为您获取坐标的方式似乎已经改变。这是我的代码

这会计算路线

func calculateRoute(from originCoor: CLLocationCoordinate2D, to destinationCoor: CLLocationCoordinate2D, completion: @escaping (Route?, Error?) -> Void ){
    let origin = Waypoint(coordinate: originCoor, coordinateAccuracy: -1, name: "Start")
    let destination = Waypoint(coordinate: destinationCoor, coordinateAccuracy: -1, name: "Finish")
    
    let options = NavigationRouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic)
            
    _ = Directions.shared.calculate(options, completionHandler: { (wayponts, result) in
        switch result {
        case .success(let response):
            guard let route = response.routes?.first else { return }
            self.directionsRoute = route
            self.drawRoute(route: self.directionsRoute!)
            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.setDirection( 00.00 , animated: true)
            
            self.mapView.setCamera(routeCam, animated: true)
            
        case .failure(let error): print(error)
        }
    })
}

这应该显示它,但正如我所说,它不起作用,因为路线没有坐标

func drawRoute(route: Route) {
     
    //Schaut, ob route überhaupt koordinaten hat, um crashes zu vermeiden
    guard route.coordinateCount > 0 else {return}
    var routeCoordinates = route.coordinates!
    
    let polyline = MGLPolylineFeature(coordinates: &routeCoordinates, count: route.coordinateCount)
    
    //Create polyline
    if let source = mapView.style?.source(withIdentifier: "route-source") as? MGLShapeSource {
        source.shape = polyline
        //Else
    } else{
        let source = MGLShapeSource(identifier: "route-source", features: [polyline], options: nil)
        
        //Create Line Style to style it
        let lineStyle = MGLLineStyleLayer(identifier: "route-style", source: source)
        lineStyle.lineColor = MGLStyleConstantValue(rawValue: UIColor.blue)
        lineStyle.lineWidth = MGLStyleConstantValue(rawValue: 4.0)
        mapView.style?.addSource(source)
        mapView.style?.addLayer(lineStyle) 
    }    
}

MGLStyleConstantValue 的最后一点似乎也有问题,但这些问题并不那么重要。我应该有所有正确的进口和正确的豆荚。 不过,Xcode 告诉我“'Route' 类型的值没有成员'坐标'”。我如何访问它们?或者:没有它们我如何绘制折线?

【问题讨论】:

    标签: swift xcode mapbox mapbox-ios


    【解决方案1】:
    func calculateRoute(from originCoor:CLLocationCoordinate2D, to destinationCoor:CLLocationCoordinate2D) {
        let origin = Waypoint(coordinate: originCoor, coordinateAccuracy: -1, name: "Start")
        let destination = Waypoint(coordinate: destinationCoor, coordinateAccuracy: -1, name: "End")
        
        let options = NavigationRouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic)
        
        _ = Directions.shared.calculate(options) { [weak self] (session, result) in
            switch result {
            case .failure(let error):
                print(error.localizedDescription)
            case .success(let response):
                guard let route = response.routes?.first, let strongSelf = self else {
                    return
                }
                
            if let leg = route.legs.first {
                for step in leg.steps {
                        if let coordinates = step.shape?.coordinates {
                            for (index, point) in coordinates.enumerated() {
                                let source = point
                                if index <= coordinates.count - 2 {
                                    let destination = coordinates[index + 1]
                                    strongSelf.getPolylineArray(source: source, destination: destination)
                                }
                            }
                        }
                        
                    }
                strongSelf.drowRoute()
                }
                let coordinateBounds = MGLCoordinateBounds(sw: destinationCoor, ne: originCoor)
                let insets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)
                let routeCam = strongSelf.mapView.cameraThatFitsCoordinateBounds(coordinateBounds, edgePadding: insets)
                strongSelf.mapView.setCamera(routeCam, animated: true)
            }
        }
    }
    
    private func getPolylineArray(source: CLLocationCoordinate2D, destination: CLLocationCoordinate2D){
        addCordinatsArray(lat: source.latitude, lon: source.longitude)
        addCordinatsArray(lat: destination.latitude, lon: destination.longitude)
        
    }
    
    func drowRoute() {
        let polyline = MGLPolylineFeature(coordinates: allCoordinates, count: UInt(allCoordinates.count))
        if let sourcce = mapView.style?.source(withIdentifier: "route-source") as? MGLShapeSource {
            sourcce.shape = polyline
        }else {
            let source = MGLShapeSource(identifier: "route-source", features: [polyline], options: nil)
            let lineStyle = MGLLineStyleLayer(identifier: "route-style", source: source)
            lineStyle.lineJoin = NSExpression(forConstantValue: "round")
            lineStyle.lineCap = NSExpression(forConstantValue: "round")
            lineStyle.lineColor = NSExpression(forConstantValue: UIColor.gray)
            
            // The line width should gradually increase based on the zoom level.
            lineStyle.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)",
                                           [14: 5, 18: 20])
            
            mapView.style?.addSource(source)
            mapView.style?.addLayer(lineStyle)
        }
    }
    

    并添加属性

     var allCoordinates: [CLLocationCoordinate2D] = []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      相关资源
      最近更新 更多