Created
July 3, 2018 20:32
-
-
Save nh7a/9f01fffc62a4c6f74e967779ce267965 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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