在 MapKit 上选择一个位置并获取经纬度

Choosing a location on MapKit and get latitude and longitude

我实现了通过 CoreLocation & CLLocation 获取当前位置。

在另一个 UIViewController 中,我想在 MapKit 上选择一个位置并从 MapKit 获取纬度和经度。我搜索了很多,但我找到了一些使用 Objective-C.

的课程

或者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)")
}

}

这是我目前所拥有的,但它不起作用...

首先,您需要将 UILongPressGestureRecognizer 添加到 MKMapView 而不是 ViewController.View

用这个

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

之后您的方法应该会按预期工作

希望这对您有所帮助