2015-12-23 15 views

Antwort

17

auf die Berührung auf der Karte reagieren Sie einen Hahn Erkenner für die mapView

in viewDidLoad einrichten müssen:

let gestureRecognizer = UITapGestureRecognizer(target: self, action:"handleTap:") 
    gestureRecognizer.delegate = self 
    mapView.addGestureRecognizer(gestureRecognizer) 

Behandeln Sie den Wasserhahn und erhalten die angezapfte Ortskoordinaten:

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) 
} 

Jetzt müssen Sie nur die Delegiertenfunktionen von MKMapView implementieren, um die Anmerkungen zu zeichnen. Eine einfache Google-Suche sollte Ihnen den Rest davon bringen.

+0

macht diese Arbeit für Sie in Swift 3? – Neo42

+1

Ich habe eine Bearbeitung für swift 3 @ Neo42 hinzugefügt. Sie werden es sehen können, sobald es überprüft wurde – KyleHodgetts

0

Für schnelle 3,0

let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.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) 
} 
1

Swift 4:

@IBOutlet weak var mapView: MKMapView! 

func handleLongPress (gestureRecognizer: UILongPressGestureRecognizer{ 
    if gestureRecognizer.state == UIGestureRecognizerState.began { 

     let touchPoint: CGPoint = gestureRecognizer.location(in: mapView) 
     let newCoordinate: CLLocationCoordinate2D = mapView.convert(touchPoint, toCoordinateFrom: mapView) 

     addAnnotationOnLocation(pointedCoordinate: newCoordinate) 
    } 
} 

func addAnnotationOnLocation(pointedCoordinate: CLLocationCoordinate2D{ 

    let annotation = MKPointAnnotation() 
    annotation.coordinate = pointedCoordinate 
    annotation.title = "Loading..." 
    annotation.subtitle = "Loading..." 
    mapView.addAnnotation(annotation) 
}