var userLocationCoordinate: CLLocationCoordinate2D?
...
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
userLocationCoordinate = userLocation.coordinate
setRegion(with: userLocation.coordinate)
}
μ΅μ΄ μ μ μ 보λ₯Ό ν΅ν΄ μ€νλλ 맡뷰μ λΈλ¦¬κ²μ΄νΈ ν¨μ μμμ ν΄λΉ κ°μ μ μμμ μ κ·Ό κ°λ₯νλλ‘ λ΄μλκΈ°
private func getDestinationRoute(from start: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D, completion: @escaping(Result<MKRoute, Error>) -> Void) {
let start = MKPlacemark(coordinate: start)
let destination = MKPlacemark(coordinate: destination)
let request = MKDirections.Request()
request.source = MKMapItem(placemark: start)
request.destination = MKMapItem(placemark: destination)
let direction = MKDirections(request: request)
direction.calculate { response, error in
guard
error == nil,
let route = response?.routes.first else {
if let error = error {
completion(.failure(error))
} else {
completion(.failure(URLError(.badURL)))
}
return
}
completion(.success(route))
}
}
MKDirections
μ λ©μλ calculate
λ₯Ό ν΅ν΄ κ²½λ‘λ₯Ό 리ν΄νλ νΈλ€λ¬ ν¨μfunc configurePolyline(with destinationCoordinate: CLLocationCoordinate2D) {
guard let userLocationCoordinate = userLocationCoordinate else { return }
getDestinationRoute(from: userLocationCoordinate, to: destinationCoordinate) { [weak self] result in
switch result {
case .success(let route):
self?.parent.mapView.addOverlay(route.polyline)
case .failure(let error): print(error.localizedDescription)
}
}
}
addOverlay
λ₯Ό ν΅ν΄ μΆκ°func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polyline = MKPolylineRenderer(overlay: overlay)
polyline.strokeColor = .systemBlue
polyline.lineWidth = 6
return polyline
}
func updateUIView(_ uiView: UIViewType, context: Context) {
if let selectedLocation = viewModel.selectedLocation {
context.coordinator.addAndSelectAnnotation(with: selectedLocation)
context.coordinator.configurePolyline(with: selectedLocation)
}
}
UIViewRepresentable
μ λ©μλ μ€ λ·°λ₯Ό μ
λ°μ΄νΈνλ μ½λ λ΄μμ λ·° λͺ¨λΈμ selectedLocation
μ κ΄μ°°ν μ΄ν ν΄λΉ μ’νλ‘μ κ²½λ‘λ₯Ό λ°μμ μ μ 그리λ λΈλ¦¬κ²μ΄νΈ ν¨μ νΈμΆ