import CoreLocation import MapKit import SwiftUI struct AttachmentLocationPickerView: View { @StateObject var locationManager = LocationManager() @State private var region = MKCoordinateRegion() @State var userInteracted: Bool = false var body: some View { Map( coordinateRegion: $region, interactionModes: .all, showsUserLocation: false, userTrackingMode: .none ) .onAppear { locationManager.start() } .onDisappear { locationManager.stop() } .onChange(of: locationManager.region) { region in if !userInteracted { let currentLoc = CLLocation(latitude: self.region.center.latitude, longitude: self.region.center.longitude) let newLoc = CLLocation(latitude: region.center.latitude, longitude: region.center.longitude) if newLoc.distance(from: currentLoc) > 10 { DispatchQueue.main.async { withAnimation { self.region = region } } } } } .overlay { Image(systemName: "mappin") .font(.title2) .foregroundColor(.Material.Elements.active) } .onChange(of: region) { region in print("Region changed: \(region.center)") } } } class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { @Published var region = MKCoordinateRegion() private let locationManager = CLLocationManager() override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest } func start() { locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } func stop() { locationManager.stopUpdatingLocation() } func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } region = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001)) } } extension MKCoordinateRegion: Equatable { public static func == (lhs: MKCoordinateRegion, rhs: MKCoordinateRegion) -> Bool { lhs.center.latitude == rhs.center.latitude && lhs.center.longitude == rhs.center.longitude && lhs.span.latitudeDelta == rhs.span.latitudeDelta && lhs.span.longitudeDelta == rhs.span.longitudeDelta } }