绘制折线MapBox,iOS

时间:2016-05-25 10:58:58

标签: ios swift mapbox

我正在创建一个使用Mapbox iOS SDK的路线的简单应用,并试图找出如何在没有geojson的情况下绘制折线。 首先,我试图用这种方法获得路线:

 func getRoute(directionsRequest: MBDirectionsRequest){

    let directionsRequest = MBDirectionsRequest(sourceCoordinate: pointOne.coordinate, destinationCoordinate: pointTwo.coordinate)
    directionsRequest.transportType = .Automobile

    let directions = MBDirections(request: directionsRequest, accessToken: "pk.eyJ1IjoidXJiaWNhIiwiYSI6ImNpb2xkNndvMjAwMW13cW1ibmY4Z2t3NHcifQ.3wadKQBcytWcJVY1eUSVWQ")


    directions.calculateDirectionsWithCompletionHandler({ (response: MBDirectionsResponse?, error: NSError?) -> Void in

        if error != nil {
            print(error)
        } else {
            self.myRoute = response?.routes.last
            print(self.myRoute?.destination.coordinate)
            self.drawRoute(self.myRoute!)
        }

    })
}

之后尝试绘制路线,但它不起作用。

func drawRoute(myRoute: MBRoute){
    let waypoints = myRoute.waypoints

    var coordinates: [CLLocationCoordinate2D] = []

    for point in waypoints {

        let coordinate = CLLocationCoordinate2DMake(point.coordinate.latitude, point.coordinate.longitude)
        coordinates.append(coordinate)
    }

    let line = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))

    dispatch_async(dispatch_get_main_queue(), {
        [unowned self] in
        self.mapView.addAnnotation(line)
        print(line)
    })
}

1 个答案:

答案 0 :(得分:3)

在这种情况下,你不应该将代码分成两个方法,结果应该是这样的

 directions.calculateDirectionsWithCompletionHandler({

        (response, error) in

        if let routeOne = response?.routes.first {

            let steps = routeOne.legs.first!.steps

            for step in steps {
                self.myTourArray.append(step)
                self.myTourArrayPoints.append(step.maneuverLocation)
            }

            self.myTourline = MGLPolyline(coordinates: &self.myTourArrayPoints, count: UInt(self.myTourArray.count))
            self.mapView.addAnnotation(self.myTourline)
        }
    })
}