How to adjust MapCameraPosition for polyline

21 Views Asked by At

in SwiftUI I am trying to display a polyline on a map and center it in the correct spot (with a bit of padding). the screen has a custom made bottom sheet that goes over the map. This is making it hard to center the polyline above. I need to move the camera down about 20-30% for it to look right. I don't know if I should be adjusting the rect that I give the camera position, adjusting the camera position after or something else.

enter image description here

Here is some of the code I am working with

import MapKit

struct MapOverviewView: View {
    @State private var cameraPosition: MapCameraPosition = .region(.userRegion)
    @State private var route: MKRoute?
    var body: some View {
        Map(position: $cameraPosition){
            Marker("My Location", coordinate: .userLocation)
                .tint(Color.theme.accentColor)
            if let route {
                MapPolyline(route.polyline)
                    .stroke(.blue,lineWidth: 4)
            }
        }
        .onAppear{
            Task { await searchRoute() }
        }
    }
    func searchRoute() async {
        print("Started")
        let request = MKDirections.Request()
        request.source = MKMapItem(placemark: .init(coordinate: .userLocation))
        request.destination = MKMapItem(placemark: .init(coordinate: CLLocationCoordinate2D(latitude: 26.3365, longitude: -81.4390)))
        print(request)
        
        Task {
            let result = try? await MKDirections(request: request).calculate()
            route = result?.routes.first
            
            if var rect = route?.polyline.boundingMapRect {

                let wPadding = rect.size.width * 0.25
                let hPadding = rect.size.height * 0.25
                            
                // Add padding to the region
                rect.size.width += wPadding
                rect.size.height += hPadding
                            
                // Center the region on the line
                rect.origin.x -= wPadding / 2
                rect.origin.y -= hPadding / 2

                cameraPosition = .rect(rect)
            }
        }
    }
}

extension CLLocationCoordinate2D {
    static var userLocation: CLLocationCoordinate2D {
        return .init(latitude: 25.7602, longitude: -80.1959)
    }
}

extension MKCoordinateRegion {
    static var userRegion : MKCoordinateRegion {
        return .init(center: .userLocation, latitudinalMeters: 10000, longitudinalMeters: 10000)
    }
}```
0

There are 0 best solutions below