swiftswiftuimkmapview

Adding waypoints/stops to a MKMapView


I'm trying to add some stops or waypoints to a route in MKMapView.

Here is the code I'm using. I have looked online but have not found any indication so far that there is a property to add a waypoint in the request object. Am I missing something? Is there a better way to do this?

   private func calculateRoute(on mapView: MKMapView, 
                            from source: CLLocationCoordinate2D,
                            to destination: CLLocationCoordinate2D) {
    let request = MKDirections.Request()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: source))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destination))

    let directions = MKDirections(request: request)
    directions.calculate { response, error in
        guard let response = response else {
            return
        }

        if let route = response.routes.first {
            mapView.addOverlay(route.polyline, level: .aboveRoads)
            mapView.setVisibleMapRect(
                route.polyline.boundingMapRect,
                edgePadding: UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50),
                animated: true)
        }
    }
}

Kind regards,


Solution

  • An MKDirections.Request has on a source and destination. If you want to add stops, then you need to request a series of routes and join them together.

    For example, if you want to travel from A to C via B, request directions from A to B and the B to C.

    You can display the poly lines as separate overlays, perhaps with markers for A,B and C. You will need to calculate the bounding rect for the combine routes