Essentially, you need a few things:
A method that builds a polyline
Track whether user location is changed. Once it's changed, call a method from previous step.
To achieve this I wrote a method:
func getDirections(to destination: CLLocationCoordinate2D) {
let sourcePlaceMark = MKPlacemark(coordinate: locationManager.coordinate!)
let sourceMapItem = MKMapItem(placemark: sourcePlaceMark)
let destinationPlacemark = MKPlacemark(coordinate: destination)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let directionsRequest = MKDirections.Request()
directionsRequest.source = sourceMapItem
directionsRequest.destination = destinationMapItem
directionsRequest.transportType = .automobile
let directions = MKDirections(request: directionsRequest)
directions.calculate { [weak self] response, error in
guard let self else { return }
guard let response else { return }
guard let primaryRoute = response.routes.first else { return }
self.overlays.append(primaryRoute.polyline)
self.steps = primaryRoute.steps
self.mapView.removeOverlays(self.overlays)
self.mapView.addOverlay(primaryRoute.polyline)
}
}
Then, you can call this method either from core location delegate method (_:didUpdateLocations:) or, I believe in your case from updateUIView of your UIViewRepresentable struct.
I just noticed, that you used UIViewRepresentable, why wouldn't you change it to UIViewControllerRepresantable? Which, I assume, would give you a better control.
One more thing, instead of go outside and test every small change there, consider to use so called GPX files, which are really powerful. However, it is up to you 😉
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: