0

I am testing Apple's KMLViewer software and I was wondering If I could use it to find in which country x,y coordinates belongs. My KML file has all the data for all countries. (Polygons, overlay..).

BlackM
  • 3,927
  • 8
  • 39
  • 69

1 Answers1

0

If you've already created your MKPolygon overlays, and your MKMapView has created the MKPolygonView views in your mapView:viewForOverlay:, and if you're just trying to see if a tap gesture is in a particular MKPolygonView, I think you can do the following:

- (void)handleTap:(UITapGestureRecognizer *)gesture
{
    BOOL success = NO;

    CGPoint location = [gesture locationInView:self.mapView];
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.mapView];
    MKMapPoint mapPoint = MKMapPointForCoordinate(coordinate);

    for (id<MKOverlay> overlay in self.mapView.overlays)
    {
        MKOverlayView *overlayView = [self.mapView viewForOverlay:overlay];
        if ([overlayView isKindOfClass:[MKPolygonView class]])
        {
            MKPolygon *polygon = (MKPolygon *)overlay;
            MKPolygonView *polygonView = (MKPolygonView *)overlayView;
            CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint];
            if (CGPathContainsPoint([polygonView path], NULL, polygonViewPoint, NO))
            {
                NSLog(@"Overlay '%@' contains point %@", polygon.title, NSStringFromCGPoint(location));
                success = YES;
                break;
            }
        }
    }

    if (!success)
        NSLog(@"No overlays contained point %@", NSStringFromCGPoint(location));
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I have coordinates (lat and lon) and I want to see in which polygon belongs. I parsed the kml as xml and get arrays for each polygon but this approach doesnt work for me: int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy). So I just thought that KMLViewer of Apple might has this function. { int i, j, c = 0; for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; } – BlackM Feb 12 '13 at 13:43
  • @user776720 I can't speak to that algorithm. I don't even see that function in the `KMViewer` sample. Sorry. – Rob Feb 12 '13 at 14:10
  • 1
    I found it here: http://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test . About the KMLViewer I didnt modified anything, I just imported the KML and I can see the map (offline) – BlackM Feb 12 '13 at 15:14