MahdiM
MahdiM

Reputation: 41

Choosing a location on MapKit and get latitude and longitude

I implemented to get the current location by CoreLocation & CLLocation.

In another UIViewController, I want to choose a location on MapKit and get latitude and longitude from MapKit. I searched a lot but I found a few courses using Objective-C.

Or is there any course in Swift?

class CustomLocationVC: UIViewController, MKMapViewDelegate, UIGestureRecognizerDelegate {

@IBOutlet weak var mapKitC: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    mapKitC.delegate = self
    let gestureZ = UILongPressGestureRecognizer(target: self, action: #selector(self.revealRegionDetailsWithLongPressOnMap(sender:)))
    view.addGestureRecognizer(gestureZ)
}

@IBAction func revealRegionDetailsWithLongPressOnMap(sender: UILongPressGestureRecognizer) {
    if sender.state != UIGestureRecognizerState.began { return }
    let touchLocation = sender.location(in: mapKitC)
    let locationCoordinate = mapKitC.convert(touchLocation, toCoordinateFrom: mapKitC)
    print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
}

}

This is what I have so far but it doesn't work...

Upvotes: 1

Views: 2062

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

First you need to add your UILongPressGestureRecognizer to your MKMapView instead of your ViewController.View

Replace your viewDidLoad method by this one

override func viewDidLoad() {
    super.viewDidLoad()
    mapKitC.delegate = self
    let gestureZ = UILongPressGestureRecognizer(target: self, action: #selector(self.revealRegionDetailsWithLongPressOnMap(sender:)))
    mapKitC.addGestureRecognizer(gestureZ)
}

After that your method should work as intended

Hope this helps

Upvotes: 2

Related Questions