Skip to content

Instantly share code, notes, and snippets.

@nh7a
Created July 3, 2018 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nh7a/9f01fffc62a4c6f74e967779ce267965 to your computer and use it in GitHub Desktop.
Save nh7a/9f01fffc62a4c6f74e967779ce267965 to your computer and use it in GitHub Desktop.
import MapKit
struct Polygon {
let coordinates: [CLLocationCoordinate2D]
let mapPoints: [MKMapPoint]
init(coordinates: [CLLocationCoordinate2D]) {
self.coordinates = coordinates
self.mapPoints = coordinates.compactMap(MKMapPointForCoordinate)
}
// http://www.faqs.org/faqs/graphics/algorithms-faq/ 2.03, How do I find if a point lies within a polygon
func contains(coordinate: CLLocationCoordinate2D) -> Bool {
guard CLLocationCoordinate2DIsValid(coordinate) else { return false }
let p = MKMapPointForCoordinate(coordinate)
var isInside = false
var j = mapPoints.count - 1
for i in 0..<mapPoints.count {
if ((mapPoints[i].y > p.y) != (mapPoints[j].y > p.y)),
(p.x < (mapPoints[j].x - mapPoints[i].x) * (p.y - mapPoints[i].y) / (mapPoints[j].y - mapPoints[i].y) + mapPoints[i].x) {
isInside = !isInside
}
j = i
}
return isInside
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment