Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
DoubleHolo Avatar asked Feb 05 '14 22:02

DoubleHolo


2 Answers

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;
}
like image 122
Michael Behan Avatar answered Nov 06 '22 01:11

Michael Behan


@mbehan answer in Swift 3+:

in ViewDidLoad:

let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourClass.foundTap(_:)))
singleTapRecognizer.delegate = self
mapView.addGestureRecognizer(singleTapRecognizer)

and the UIGestureRecognizerDelegate extension:

extension YourClass: UIGestureRecognizerDelegate {
  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    return !(touch.view is MKPinAnnotationView)
  }
}
like image 24
Federico Zanetello Avatar answered Nov 06 '22 03:11

Federico Zanetello