This commit is contained in:
fmodf 2024-07-04 16:25:25 +02:00
parent 528e474d91
commit c3679c9a2a

View file

@ -1,79 +1,42 @@
import Combine
import CoreLocation import CoreLocation
import MapKit import MapKit
import SwiftUI import SwiftUI
struct AttachmentLocationPickerView: View { struct AttachmentLocationPickerView: View {
@StateObject var locationManager = LocationManager() @State var region = MKCoordinateRegion()
@State private var region = MKCoordinateRegion() @State var userTrackingMode: MapUserTrackingMode = .follow
@State var userInteracted: Bool = false
var body: some View { var body: some View {
Map( ZStack {
coordinateRegion: $region, Map(
interactionModes: .all, coordinateRegion: $region,
showsUserLocation: false, interactionModes: .all,
userTrackingMode: .none showsUserLocation: false,
) userTrackingMode: $userTrackingMode
.onAppear { )
locationManager.start() .overlay {
} Image(systemName: "mappin")
.onDisappear { .resizable()
locationManager.stop() .frame(width: 30, height: 30)
} .foregroundColor(.Material.Elements.active)
.onChange(of: locationManager.region) { region in if userTrackingMode != .follow {
if !userInteracted { VStack {
let currentLoc = CLLocation(latitude: self.region.center.latitude, longitude: self.region.center.longitude) Spacer()
let newLoc = CLLocation(latitude: region.center.latitude, longitude: region.center.longitude) HStack {
if newLoc.distance(from: currentLoc) > 10 { Spacer()
DispatchQueue.main.async { Image(systemName: "location.north.circle.fill")
withAnimation { .resizable()
self.region = region .frame(width: 30, height: 30)
.foregroundColor(.Material.Elements.active)
.padding()
.tappablePadding(.symmetric(10)) {
userTrackingMode = .follow
}
} }
} }
} }
} }
} }
.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
} }
} }