2024-07-04 11:45:39 +00:00
|
|
|
import CoreLocation
|
2024-07-02 09:56:27 +00:00
|
|
|
import MapKit
|
|
|
|
import SwiftUI
|
|
|
|
import UIKit
|
|
|
|
|
|
|
|
struct AttachmentLocationPickerView: View {
|
2024-07-04 11:45:39 +00:00
|
|
|
@StateObject private var locationManager = LocationManager()
|
2024-07-02 09:56:27 +00:00
|
|
|
@State private var region = MKCoordinateRegion(
|
|
|
|
center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
|
|
|
|
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
|
|
|
|
)
|
|
|
|
|
|
|
|
var body: some View {
|
|
|
|
MapView(coordinateRegion: $region)
|
2024-07-04 11:45:39 +00:00
|
|
|
.onAppear {
|
|
|
|
locationManager.start()
|
|
|
|
}
|
|
|
|
.onChange(of: locationManager.lastLocation) { newLocation in
|
|
|
|
if let newLocation {
|
|
|
|
region.center = newLocation.coordinate
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
|
|
|
|
private let locationManager = CLLocationManager()
|
|
|
|
@Published var lastLocation: CLLocation?
|
|
|
|
|
|
|
|
override init() {
|
|
|
|
super.init()
|
|
|
|
locationManager.delegate = self
|
|
|
|
}
|
|
|
|
|
|
|
|
func start() {
|
|
|
|
locationManager.requestWhenInUseAuthorization()
|
|
|
|
locationManager.startUpdatingLocation()
|
|
|
|
}
|
|
|
|
|
|
|
|
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
|
|
|
lastLocation = locations.first
|
2024-07-02 09:56:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct MapView: UIViewRepresentable {
|
|
|
|
@Binding var coordinateRegion: MKCoordinateRegion
|
|
|
|
|
|
|
|
func makeUIView(context: Context) -> MKMapView {
|
|
|
|
let mapView = MKMapView()
|
|
|
|
mapView.delegate = context.coordinator
|
|
|
|
return mapView
|
|
|
|
}
|
|
|
|
|
|
|
|
func updateUIView(_ uiView: MKMapView, context _: Context) {
|
|
|
|
uiView.setRegion(coordinateRegion, animated: true)
|
|
|
|
}
|
|
|
|
|
|
|
|
func makeCoordinator() -> Coordinator {
|
|
|
|
Coordinator(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
class Coordinator: NSObject, MKMapViewDelegate {
|
|
|
|
var parent: MapView
|
|
|
|
|
|
|
|
init(_ parent: MapView) {
|
|
|
|
self.parent = parent
|
|
|
|
}
|
|
|
|
|
|
|
|
func mapView(_ mapView: MKMapView, regionDidChangeAnimated _: Bool) {
|
|
|
|
parent.coordinateRegion = mapView.region
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|