简体   繁体   中英

Draw polyline MapBox, iOS

I'm creating a simple app with routes using Mapbox iOS SDK and trying to find out how to draw a polyline without geojson. First of all I tried to get the route with this method:

 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!)
        }

    })
}

And after that tried to draw a route, but it doesn't work.

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)
    })
}

In this situation you shouldn't divide code into two methods and result should look like this

 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)
        }
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM