Skip to content

Instantly share code, notes, and snippets.

@rockarts
Created March 22, 2017 05:41
Show Gist options
  • Select an option

  • Save rockarts/e9bb4232ab293cc24d523138fc0561b2 to your computer and use it in GitHub Desktop.

Select an option

Save rockarts/e9bb4232ab293cc24d523138fc0561b2 to your computer and use it in GitHub Desktop.
Checking for point in polygon
func IsPointInPolygon(p: CLLocationCoordinate2D, polygon: [CLLocationCoordinate2D]) -> Bool {
var minX: Double = polygon[0].latitude
var maxX: Double = polygon[0].latitude
var minY: Double = polygon[0].longitude
var maxY: Double = polygon[0].longitude
for i in 0...polygon.count{
let q : CLLocationCoordinate2D = polygon[i];
minX = min(q.latitude, minX)
maxX = max(q.latitude, maxX)
minY = min(q.longitude, minY)
maxY = max(q.longitude, maxY)
}
if ( p.latitude < minX || p.latitude > maxX || p.longitude < minY || p.longitude > maxY )
{
return false
}
var inside : Bool = false;
for ( int i = 0, j = polygon.Length - 1 ; i < polygon.Length ; j = i++ )
{
if ( ( polygon[i].longitude > p.longitude ) != ( polygon[j].longitude > p.longitude ) &&
p.X < ( polygon[j].latitude - polygon[i].latitude ) * ( p.longitude - polygon[i].longitude ) / ( polygon[j].longitude - polygon[i].longitude ) + polygon[i].latitude )
{
inside = !inside;
}
}
return inside;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment