detect if a point is inside a MKPolygon overlay

后端 未结 6 1943
余生分开走
余生分开走 2020-12-07 23:44

I want to be able to tell if tap is within a MKPolygon.

I have a MKPolygon:

CLLocationCoordinate2D  points[4];

points[0] = CLLocationCoordinate2DMak         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 23:50

    I created this MKPolygon category in case anyone wants to use it. Seems to work well. You have to account for the interior polygons (i.e. holes in the polygon):

    @interface MKPolygon (PointInPolygon)
      -(BOOL) pointInPolygon:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView;
    @end
    
    @implementation MKPolygon (PointInPolygon)
    
    -(BOOL) pointInPolygon:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView {
        MKMapPoint mapPoint = MKMapPointForCoordinate(point);
        MKPolygonView * polygonView = (MKPolygonView*)[mapView viewForOverlay:self];
        CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint];
        return CGPathContainsPoint(polygonView.path, NULL, polygonViewPoint, NO) && 
            ![self pointInInteriorPolygons:point mapView:mapView];
    }
    
    -(BOOL) pointInInteriorPolygons:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView {
        return [self pointInInteriorPolygonIndex:0 point:point mapView:mapView];
    }
    
    -(BOOL) pointInInteriorPolygonIndex:(int) index point:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView {
        if(index >= [self.interiorPolygons count])
            return NO;
        return [[self.interiorPolygons objectAtIndex:index] pointInPolygon:point mapView:mapView] || [self pointInInteriorPolygonIndex:(index+1) point:point mapView:mapView];
    }
    
    @end
    

提交回复
热议问题