Hey guys,
I recently started using Swiftui and would like to make a small app for my dad to use as a travel journal as my first project.
He can create trips and then create multiple steps in a trip. When creating a step he should be able to set a location.
Finding the location from the user is no problem. But now I also want to have the function to tap on the map and set a pin at a random location to get the coordinates (like google maps for example).
Unfortunately I can't figure out from the documentation if there is a simple way to do this.
import SwiftUI
import MapKit
struct StepLocationView: View {
@EnvironmentObject var locationManagement: LocationDataManager
@State private var position: MapCameraPosition = .automatic
var body: some View {
VStack {
Map(position: $position) {
UserAnnotation()
}
.navigationTitle("Search your location")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
.toolbarBackground(.ultraThinMaterial, for: .navigationBar)
.edgesIgnoringSafeArea(.bottom)
.onAppear{
position = .region(locationManagement.region)
}
.mapStyle(.standard(elevation: .realistic))
.mapControls {
MapUserLocationButton()
MapPitchButton()
}
}
.background(Color.white)
}
}
import SwiftUI
import MapKit
class LocationDataManager : NSObject, ObservableObject {
@Published var location: CLLocation?
@Published var region = MKCoordinateRegion()
private let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation() // info.plist has to be updated
locationManager.delegate = self
}
}
extension LocationDataManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
self.location = location
self.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude), latitudinalMeters: 5000, longitudinalMeters: 5000)
};
}
I really appreciate your help,
Marius