2

I'm trying to get the MKAnnotationView that displays the user location (blue dot) in MapKit to add a custom gesture recognizer. Is this possible?

I've tried via the delegate method but I don't know how to dequeue the view when I don't have the identifier string. If I had the identifier I could probably do something like the code below;

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

    if annotation is MKUserLocation {
        let userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "??", for: annotation)
        userLocationAnnotationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleStuff)))
        return userLocationAnnotationView
    }
}

EDIT

Ah, been stuck on this for hours and found the solution directly after I posted. I found two different ways of solving it with delegate methods. The first way could be via didSelect:

func mapView(_ mapView: MKMapView,
             didSelect view: MKAnnotationView){
    if view.annotation is MKUserLocation {
        // User clicked on the blue dot
    }
}

Or if a gesture recognizer is needed it could be done as below. Should probably add a check if the gesture recognizer already have been added since this function gets called every time an annotation view is added.

func mapView(_ mapView: MKMapView,
                      didAdd views: [MKAnnotationView]){
    for view in views {
        if view.annotation is MKUserLocation {
            view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleStuff)))
        }
    }
}
gugge
  • 918
  • 1
  • 11
  • 17
  • I don't think you can handle the default blue dot to have custom gesture. Try by adding your own annotation view that looks similar to the blue dot and add the gesture to it. – Satyam Oct 28 '18 at 16:26
  • @Satyam Thanks for the reply. I found a solution that worked for me without creating a custom annotation, updated the question with my solution. – gugge Oct 28 '18 at 16:54

0 Answers0