Home > Net >  How to track the Latitude and Longitude at the center of a MapView in SwiftUI?
How to track the Latitude and Longitude at the center of a MapView in SwiftUI?

Time:04-26

I would like to create a MapView which keeps track of the longitude and latitude at the center of the MapView, and stores it in two state variables. How can I track the latitude/longitude in such a way?

I've tried using the region to see if the center updates with the map movements, but unfortunately it doesn't:

@State private var region: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40.75773, longitude: -73.985708), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
var body: some View {
        ZStack {
            Map(coordinateRegion: $viewModel.region,
                showsUserLocation: true,
                annotationItems: getNearbyEvents()
            ) {/* places annotations on the map */}
            }
                .edgesIgnoringSafeArea(.all)
                .accentColor(Color("BlueAccent"))
                .onAppear {
                    viewModel.checkLocationServicesEnabled()
                }
            // Displays region center as text... doesn't update with movement :(
            Text("Long: \(region.center.longitude) Lat: \(region.center.latitude)")
        }
    }

CodePudding user response:

viewModel.region is not the same as region that is being used in the Text use viewModel.region instead.

Text("Long: \(viewModel.region.center.longitude) Lat: \(viewModel.region.center.latitude)")

CodePudding user response:

Assign region for Map like:

region = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: self.zoomLevel, longitudeDelta: self.zoomLevel))
  • Related