Hi guys! I am a beginner in SwiftUI. I have a problem in my code and could not find an Internet article about it. Here is the full code:
import SwiftUI
import MapKit
struct Place: Identifiable {
let id = UUID()
let name: String
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
@State private var showingPopover = false
@State private var selectedPlaceName = "ERROR"
let places = [
Place(name: "…", latitude: 0.0, longitude: 0.0)
]
@State var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 48.71424,
longitude: 8.741835
),
span: MKCoordinateSpan(
latitudeDelta: 0.01 ,
longitudeDelta: 0.01
)
)
var body: some View {
Map(
coordinateRegion: $region,
showsUserLocation: true,
annotationItems: places) { place in
MapAnnotation(coordinate: place.coordinate) {
Image(systemName: "pin.fill")
.foregroundColor(Color.red)
.onTapGesture(count: 1, perform: {
selectedPlaceName = place.name;
showingPopover = true
}
)
}
}
.accentColor(Color(.systemBlue))
.statusBar(hidden: true)
.onAppear{
viewModel.checkIfLocationServicesIsEnabled()
}
.popover(isPresented: $showingPopover){
Text("Description:" + selectedPlaceName)
}
}
final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 0.0,
longitude: 0.0
),
span: MKCoordinateSpan(
latitudeDelta: 0.01 ,
longitudeDelta: 0.01
)
)
var locationManager: CLLocationManager?
func checkIfLocationServicesIsEnabled() {
if CLLocationManager.locationServicesEnabled() {
locationManager = CLLocationManager()
locationManager?.delegate = self
} else {
print("Please turn on location in the settings.")
}
}
private func checkLocationAuthorization() {
guard let locationManager = locationManager else { return }
switch locationManager.authorizationStatus {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
print("Please activate location services in the settings.")
case .denied:
print("You have deactivated location services, please activate it in the installations.")
case .authorizedAlways, .authorizedWhenInUse:
region = MKCoordinateRegion(center: locationManager.location!.coordinate, span: MKCoordinateSpan(
latitudeDelta: 0.1,
longitudeDelta: 0.1
))
@unknown default:
break
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
}
}
This is the part that causes me difficulties:
annotationItems: places) { place in
MapAnnotation(coordinate: place.coordinate) {
Image(systemName: "pin.fill")
.foregroundColor(Color.red)
.onTapGesture(count: 1, perform: {
selectedPlaceName = place.name;
showingPopover = true
}
I want to set the variable „selectedPlaceName“ before setting „showingPopover“
I don’t know how to proceed. Can you help me? Thanks!