TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Gesture on map

Forums > SwiftUI

Hi, I'm currently working on a spot tracking app, which means it's on a user-defined geographical area. I have a problem, I don't know how to get the coordinates of the place where the user presses on the map and convert them in order to get the geographic coordinates for further processing. Here's my code: if you have any ideas, don't hesitate ^^thanks in advance :)

import SwiftUI
import CoreLocation
import MapKit

struct AddZoneView: View {

    let locationManager = Location()
    let viewController = AddZoneController()
    @State var pinLocation: CLLocationCoordinate2D?
    @State private var userLocation: CLLocationCoordinate2D?

    var body: some View {
        NavigationView {
            Map(coordinateRegion: .constant(MKCoordinateRegion(
                center: userLocation ?? CLLocationCoordinate2D(
                    latitude: locationManager.userLocation?.latitude ?? 0,
                    longitude: locationManager.userLocation?.longitude ?? 0
                ),
                span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
            )), showsUserLocation: true)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .onTapGesture { gesture in
                let tap = gesture.location
                pinLocation = coordinate(for: tap)
                viewController.addMarker(longitude: pinLocation?.longitude ?? 0, latitude: pinLocation?.latitude ?? 0)

            }
            .ignoresSafeArea(.all)
        }
        func coordinate(for location: CGPoint) -> CLLocationCoordinate2D {
            let mapRect = MKMapRect(
                origin: MKMapPoint(x: location.x, y: location.y),
                size: MKMapSize(width: 0, height: 0)
            )
            let coordinate = mapRect.origin.coordinate
            return coordinate
        }
    }
}

#Preview {
    AddZoneView()
}

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.