9

In the app I'm currently designing I have a MKMapView with overlays on it (customized MKPolylines btw) and I would like to be able to detect touch events on these overlays and assign a specific action to each overlay. Could any one help me on this one ? Thanks !

Benja

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
Ben
  • 193
  • 2
  • 13

2 Answers2

19

This can be solved combining How to intercept touches events on a MKMapView or UIWebView objects? and How to determine if an annotation is inside of MKPolygonView (iOS). Add this in viewWillAppear:

WildcardGestureRecognizer * tapInterceptor = [[WildcardGestureRecognizer alloc] init];
tapInterceptor.touchesBeganCallback = ^(NSSet * touches, UIEvent * event) {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.mapView];

    CLLocationCoordinate2D coord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    MKMapPoint mapPoint = MKMapPointForCoordinate(coord);
    for (id overlay in self.mapView.overlays) 
    {
        if ([overlay isKindOfClass:[MKPolygon class]])
        {
            MKPolygon *poly = (MKPolygon*) overlay;
            id view = [self.mapView viewForOverlay:poly];
            if ([view isKindOfClass:[MKPolygonView class]])
            {
                MKPolygonView *polyView = (MKPolygonView*) view;
                CGPoint polygonViewPoint = [polyView pointForMapPoint:mapPoint];
                BOOL mapCoordinateIsInPolygon = CGPathContainsPoint(polyView.path, NULL, polygonViewPoint, NO);   
                if (mapCoordinateIsInPolygon) {
                    debug(@"hit!") 
                } else {
                    debug(@"miss!");   
                }
            }
        }
    }

};
[self.mapView addGestureRecognizer:tapInterceptor];

WildcardGestureRecognizer is in the first linked answer. Calling mapView:viewForOverlay: won't be cheap, adding a local cache of those would help.

Community
  • 1
  • 1
Jano
  • 62,815
  • 21
  • 164
  • 192
  • Brilliant. This is exactly the code I was looking for to detect when tapping on an overlay. However I put it inside the method called buy a tap gesture recogniser. Works just fine without having to create a custom interceptor. – drekka Apr 10 '12 at 01:56
  • This Stopped working on iOS7! where polyView.path is always nil! – Bach Sep 16 '13 at 08:35
  • 5
    Replace MKPolygonView with MKPolygonRenderer - the former was deprecated in iOS7 – guyh92 Dec 23 '13 at 10:45
0

Just in case it might help some of you... I couldn't find a way to do that but I added an annotation on my overlays (Anyway, i needed to do that to display some information) and then I could get the touch event on this annotation. I know it is not the best way to do it but in my situation, and maybe yours, it works ;) !

Ben
  • 193
  • 2
  • 13