Home > other >  How can I make map route instructions clickable on SwiftUI?
How can I make map route instructions clickable on SwiftUI?

Time:03-17

I have a simple map made with "pure" SwiftUI. There is a search bar to search a place and when I click the "Go" button it shows the instructions of how to go that place from a particular location. It shows it below the map, on the "Enter a destination" field. What I want to do is, I want these instructions to be clickable. When I click each of the instructions it should zoom in that particular place where the instruction takes place. Right now it's only a list of text. Is it possible to do it without using UIViewRepresentable? And how can I do it?

I tried with

.onTapGesture {
                    region.span = MKCoordinateSpan(latitudeDelta: region.span.latitudeDelta/2, longitudeDelta: region.span.longitudeDelta/2)
                }

but it zooms in the same location on every instruction I click.

ContentView

struct Location: Identifiable {
let id = UUID()
let name: String
let coordinate: CLLocationCoordinate2D
}

struct RouteSteps: Identifiable {
    let id = UUID()
    let step: String
}
    
struct ContentView: View {
@State private var searchBar: String = ""
    @State private var home = CLLocationCoordinate2D(latitude: 39.90068, longitude: 32.86081)
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 39.90068, longitude: 32.86081), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    @State var routeSteps: [RouteSteps] = [RouteSteps(step: "Enter a destination")]
    @State var annotations = [Location(name: "Ankara", coordinate: CLLocationCoordinate2D(latitude: 39.90068, longitude: 32.86081))]
    var body: some View {
        VStack{
             HStack {
            TextField("", text: $searchBar)
            Button("Go") {
                findNewLocation()
            }
            .frame(width: 35, height: 35)
            .foregroundColor(Color.white)
            .background(Color.blue)
            .cornerRadius(5)
             }.textFieldStyle(.roundedBorder).colorInvert()
            Map(coordinateRegion: $region, annotationItems: annotations){ item in
                MapMarker(coordinate: item.coordinate)
            }.frame(width: 400, height: 300)
            List(routeSteps) { r in
                Text(r.step)
            }

route function in ContentView

func findNewLocation(){
    let searchResult = searchBar
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(searchResult, completionHandler:
    {(placemarks, error) -> Void in
        if((error) != nil){
            print("error at geocode")
        }
        if let placemark = placemarks?.first {
            let coordinates : CLLocationCoordinate2D = placemark.location!.coordinate
            region = MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
            annotations.append(Location(name: placemark.name!, coordinate: coordinates))
            let request = MKDirections.Request()
            request.source = MKMapItem(placemark: MKPlacemark(coordinate: home, addressDictionary: nil))
            request.destination = MKMapItem(placemark: MKPlacemark(coordinate: coordinates, addressDictionary: nil))
            request.requestsAlternateRoutes = false 
            request.transportType = .automobile 
    
            let directions = MKDirections(request: request)
            directions.calculate(completionHandler: { response, error in
                for route in (response?.routes)! {
                    self.routeSteps = []
                    for step in route.steps {
                        self.routeSteps.append(RouteSteps(step: step.instructions))
                    }
                }
            })
        }
    })
}

CodePudding user response:

Yes, but you have to stop throwing away the data. MKRoute.Steps actually gives you all of the information you need, so first, set up RouteSteps to accept MKRoute.Steps:

struct RouteSteps: Identifiable {
    let id = UUID()
    let step: MKRoute.Step
}

Then, in your findNewLocation() function:

func findNewLocation(){
    ...
    directions.calculate(completionHandler: { response, error in
                // I used a guard statement to get rid of your force unwrap.
                // NEVER force unwrap in a situation like this.
                // Implement error handling here
                guard let response = response else { return } 
                for route in response.routes {
                    // Map the MKRoute.Steps to your struct
                    self.routeSteps = route.steps.map( { RouteSteps(step: $0) } )
                }
            })
    ...

}

Then in the main part of your ContentView:

struct ContentView: View {
    ...

    var body: some View {
        ...
            List(routeSteps) { routeStep in
                // Pull your instructions out here
                Text(routeStep.step.instructions)
                    .onTapGesture {
                        // The MKRoute.Step contains an overlay polyline for MKMapKit.
                        // We can't use that in SwiftUI maps yet, but the polyline contains a
                        // boundingMapRect that we can use to change the region shown on the map
                        // with the MKCoordinateRegion(_ MKMapRect) initializer. Setting the region
                        // to the insturction's polyline boundingMapRect does exactly what you want.
                        region = MKCoordinateRegion(routeStep.step.polyline.boundingMapRect)
                    }
            }
        ...
}
  • Related