I have a KML file that contains all the polygons coordinates for all countries.
Some countries have more than 1 <coordinates>
tag.
What I am trying to accomplish here is to get a coordinates and find in which polygon is located. I got an idea on this post but my problem is that my algorithm is wrong and returns that my coordinates are located on more than 1 polygons.
This is my code:
-(void)parseCoordinates:(NSString*)str{
coordinatesArray = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSInteger coordinatesCount = [coordinatesArray count];
CLLocationCoordinate2D *cord2d = malloc(sizeof(CLLocationCoordinate2D) * coordinatesCount);
for(int i=0; i<coordinatesCount;i++){
NSString *st = [coordinatesArray objectAtIndex:i];
if ([st isEqualToString:@""]) {
continue;
}
NSArray *strArray = [st componentsSeparatedByString:@","];
if ([strArray count]>1) {
cord2d[i] = CLLocationCoordinate2DMake([[strArray objectAtIndex:1] doubleValue], [[strArray objectAtIndex:0] doubleValue]);
}
strArray=nil;
}
free(cord2d);
coordinatesArray = nil;
MKPolygon* poly2 = [MKPolygon polygonWithCoordinates:cord2d count:coordinatesCount];
CLLocationCoordinate2D mapCoordinate = CLLocationCoordinate2DMake(39.1274378,-100.9945566);
MKMapPoint mapPoint = MKMapPointForCoordinate(mapCoordinate);
MKPolygonRenderer *polygonView = [[MKPolygonRenderer alloc]initWithPolygon:poly2];
CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint];
BOOL mapCoordinateIsInPolygon =
CGPathContainsPoint(polygonView.path, NULL, polygonViewPoint, NO);
NSLog(@"Country: %@", country);
NSLog(@"is it inside? %d",mapCoordinateIsInPolygon);
}