DoubleHolo DoubleHolo - 1 year ago 74
iOS Question

iOS MapView: Add Annotation on tap, but not if existing Annotation Tapped

I have a UITapGestureRecognizer setup to add an annotation onto the map where the user clicks. The problem I'm running into is when the user taps an existing annotation to view the tooltip, the tooltip pops up, but another annotation is added to the map behind the clicked annotation. Is there a way to detect if an annotation was tapped and return before adding the annotation?

This is my viewDidLoad:

UITapGestureRecognizer *singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foundTap:)];
singleTapRecognizer.numberOfTapsRequired = 1;
[self.mapView addGestureRecognizer:singleTapRecognizer];

And my on touch function:

-(IBAction)foundTap:(UITapGestureRecognizer *)recognizer
CGPoint point = [recognizer locationInView:self.mapView];

CLLocationCoordinate2D tapPoint = [self.mapView convertPoint:point toCoordinateFromView:self.view];

AGIAnnotation * annotation = [[AGIAnnotation alloc] initWithCoordinate:tapPoint];
// Some other stuff

[self.mapView addAnnotation:annotation];

Any help is appreciated.

Answer Source

There is a UIGestureRecognizerDelegate Protocol

Implement gestureRecognizer:shouldReceiveTouch: and return NO if the touch is on an existing tooltip. Something like this:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
    if ([touch.view isKindOfClass:[MKPinAnnotationView class]])
        return NO;
    return YES;