我想在触摸iOS地图时添加注释并获取相应位置的详细地址(地标).我如何在Swift中实现这一目标?
提前致谢.
要对地图上的触摸做出反应,您需要为mapView设置点按识别器
在viewDidLoad
:
let gestureRecognizer = UITapGestureRecognizer(target: self, action:"handleTap:") gestureRecognizer.delegate = self mapView.addGestureRecognizer(gestureRecognizer)
处理水龙头并获取轻敲的位置坐标:
func handleTap(gestureReconizer: UILongPressGestureRecognizer) { let location = gestureReconizer.locationInView(mapView) let coordinate = mapView.convertPoint(location,toCoordinateFromView: mapView) // Add annotation: let annotation = MKPointAnnotation() annotation.coordinate = coordinate mapView.addAnnotation(annotation) }
现在,您只需实现MKMapView委托函数来绘制注释.一个简单的谷歌搜索应该可以让你完成剩下的工作.
这是一个工作正常的Xcode 10.1,Swift 4.2项目,具有MapKit委托来控制注释(图钉颜色,图钉图像等),并委托来处理对添加的注释的单击: Github Project
import UIKit import MapKit class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self let longTapGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap)) mapView.addGestureRecognizer(longTapGesture) } @objc func longTap(sender: UIGestureRecognizer){ print("long tap") if sender.state == .began { let locationInView = sender.location(in: mapView) let locationOnMap = mapView.convert(locationInView, toCoordinateFrom: mapView) addAnnotation(location: locationOnMap) } } func addAnnotation(location: CLLocationCoordinate2D){ let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "Some Title" annotation.subtitle = "Some Subtitle" self.mapView.addAnnotation(annotation) } } extension ViewController: MKMapViewDelegate{ func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard annotation is MKPointAnnotation else { print("no mkpointannotaions"); return nil } let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.rightCalloutAccessoryView = UIButton(type: .infoDark) pinView!.pinTintColor = UIColor.black } else { pinView!.annotation = annotation } return pinView } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { print("tapped on pin ") } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { if let doSomething = view.annotation?.title! { print("do something") } } } }