3

How do I detect if the mapview is being tapped on, that isn't an annotation in obj-c?

Tim Nuwin
  • 2,775
  • 2
  • 29
  • 63
  • Strangely, you just add the usual tap detection code - it seems that MapView does not have the concept "built-in"! – Fattie Apr 17 '17 at 20:25

3 Answers3

2

Swift 4,

I fixed this in our case, by adding tap gestures to both annotation view and map view.

add tap gesture to map

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.hideFilterView))
self.mapView.addGestureRecognizer(tapGesture)

//override "viewFor annotation:" something like this
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin")
    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "Pin"
        annotationView?.canShowCallout = false
    } else {
        annotationView?.annotation = annotation
    }
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.didTapPin(onMap:)))
    annotationView?.addGestureRecognizer(tapGesture)

    return annotationView
}

//then don't override 
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { }

So the all pins selections will be handled using tap gestures. And you can detect map and pins tap separately.

Community
  • 1
  • 1
Pramod More
  • 1,220
  • 2
  • 22
  • 51
0

Try UITapGestureRecognizer:

UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] 
   initWithTarget:self action:@selector(mapDidTap:)];
[mapView addGestureRecognizer: tapGesture];

And

-(void)mapDidTap:(UITapGestureRecognizer *)gestureRecognizer {
    //do something when map is tapped
}
Ty Lertwichaiworawit
  • 2,950
  • 2
  • 23
  • 42
0

The following code detects a tap in the map and adds a map marker at that location:

- (void)viewDidLoad {
    [super viewDidLoad];

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

}

- (void)handleMapFingerTap:(UIGestureRecognizer *)gestureRecognizer {

    NSLog(@"handleMapFingerTap gesture: %@", gestureRecognizer);

    if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
        return;
    }

    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
    CLLocationCoordinate2D touchMapCoordinate =
    [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];

    MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
    pa.coordinate = touchMapCoordinate;
    pa.title = @"Hello";
    [self.mapView addAnnotation:pa];

}
Stewart Macdonald
  • 2,062
  • 24
  • 27