UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Update the route line when user change current location

Forums > SwiftUI

I created a map that show routes and directions from current location to the destination, I want to achieve following:

  1. I want to always change beginning of polyline on the current location,
  2. I want to always recalculate if user lost their first path.

This is my code:

struct MapView: UIViewRepresentable {
typealias UIViewType = MKMapView

@Binding var directions: [String]

func makeCoordinator() -> MapViewCoordinator {
    return MapViewCoordinator()
}

func makeUIView(context: Context) -> MKMapView {
    let mapView = MKMapView()

    mapView.delegate = context.coordinator
    mapView.showsUserLocation = true

    let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 43.58393, longitude: 19.52201), span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    mapView.setRegion(region, animated: true)

    let locationManager = CLLocationManager()
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = context.coordinator
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    // Prijepolje
    let p2 = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 43.000000, longitude: -75.000000))

    let request = MKDirections.Request()

    request.source = MKMapItem.forCurrentLocation()
    request.destination = MKMapItem(placemark: p2)
    request.transportType = .automobile

    let directions = MKDirections(request: request)

    directions.calculate { response, error in
        guard let route = response?.routes.first else {
            return
        }
        mapView.addAnnotations([p2])
        mapView.addOverlay(route.polyline)
        mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20), animated: true)
        self.directions = route.steps.map { $0.instructions }.filter {
            !$0.isEmpty
        }
    }

    return mapView
}

func updateUIView(_ uiView: MKMapView, context: Context) {

}

class MapViewCoordinator: NSObject, MKMapViewDelegate, CLLocationManagerDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer  = MKPolylineRenderer(overlay: overlay)

        renderer.strokeColor = .blue
        renderer.lineWidth = 5
        return renderer
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            // Do something with the updated location if needed
        }
    }
}
}

This is my current behaviour, the directions and route are only created when MapView is called, and never updated again.

I'm using Xcode 14.2, and iPhone 11.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.