Xcode Directions coordinate in Swift

513 Views Asked by At

I have this code to get directions from a source point(userLocation) to a annotation(pin choosed from user).`

    func showRouteOnMap() {
    let request = MKDirectionsRequest()

    request.source = MKMapItem(placemark: MKPlacemark(coordinate: (userLocationForDirections?.coordinate)!, addressDictionary: nil))
    if(annotationPin != nil){
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate:  (coordinateAnnotationPin)!, addressDictionary: nil))
    }
    request.requestsAlternateRoutes = true
    request.transportType = .walking

    let directions = MKDirections(request: request)

    directions.calculate(completionHandler: {(response, error) in

        if error != nil {
            print("Error getting directions")

        } else {
            self.showRoute(response!)
        }
    })
}

Now I need to get the coordinate of the direction route (CLLocationCordinate2D). How can I do?

1

There are 1 best solutions below

0
On BEST ANSWER

This is how you get the coordinates from a polyline. Although you should just need to add the polyline to your map. It is unusual to require the coordinates.

let directions = MKDirections(request: request)

directions.calculate { (response, error) in

    if let error = error {

        print(error.localizedDescription)

        return
    }

    if let response = response {

        if let route = response.routes.first {

            self.map.add(route.polyline, level: .aboveRoads)

            let coordinates: Array<CLLocationCoordinate2D> = {

                var array = Array<CLLocationCoordinate2D>()

                let polyline = route.polyline

                for i in 0 ..< polyline.pointCount {

                    let point = polyline.points()[i]

                    array.append(MKCoordinateForMapPoint(point))
                }

                return array
            }()

            dump(coordinates)
        }
    }
}