Mapkit获取地标的当前坐标

时间:2019-03-21 02:54:39

标签: swift mapkit mapkitannotation

我对MapKit相当陌生,并且一旦选择了位置标记,便尝试显示信息和方向。我正在展示当地的医院和急救服务。如何获取当前所选地标的信息。我希望能够显示有关所选标记的几行信息。例如名称,地址,电话号码,以及可能的方向按钮。我想将当前选定的标记坐标保存到变量中。

maps image

class MapKitViewController: UIViewController, MKMapViewDelegate {


let locationManager = CLLocationManager()
let regionInMeters: Double = 10000
var previousLocation: CLLocation?

let geoCoder = CLGeocoder()
var directionsArray: [MKDirections] = []



func setupLocationManager() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
}

func centerViewOnUserLocation() {
    if let location = locationManager.location?.coordinate {
        let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)
    }
}


func checkLocationServices() {
    if CLLocationManager.locationServicesEnabled() {
        setupLocationManager()
        performSearch()
        checkLocationAuthorization()
    } else {
        // Show alert letting the user know they have to turn this on.
    }
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation)
    -> MKAnnotationView? {

        let identifier = "marker"
        var view: MKMarkerAnnotationView

        if let dequeuedView = mapView.dequeueReusableAnnotationView(
            withIdentifier: identifier)
            as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view =
                MKMarkerAnnotationView(annotation: annotation,
                                       reuseIdentifier: identifier)


            view.markerTintColor = UIColor.blue
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)

        }
        return view
}

func mapView(_: MKMapView, annotationView:
    MKAnnotationView, calloutAccessoryControlTapped: UIControl) {


    print("Control tapped")
}

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {


}

1 个答案:

答案 0 :(得分:0)

原始注释类(MKPointAnnotation)不允许您向钉子提供除了标题和副标题以外的更多信息。因此,您需要从MKPointAnnotation中创建一个子类,以便可以唯一标识用户点击的引脚,MKMapView的{​​{1}}委托方法会检测到该引脚。

首先,如下创建一个名为MyPointAnnotation的快速文件。

didSelect

然后使用上面的子类进行注释并将其添加到地图中。

import MapKit

class MyPointAnnotation: MKPointAnnotation {
    var identifier: String?
    //var image: UIImage?
    var lat: Double!
    var lon: Double!
}