swiftcgpathmapkitannotationcgpathrefmkcircle

Using MKCircle to detect if CGPathContainsPoint in Swift 2.0


I'm trying to detect if a Map Annotation is inside an MKCircle. I have tirelessly traversed the internet with little luck of finding a solid tutorial of this for Swift 2.0. All tutorial or Stack Overflow questions are answered with deprecated code or for Objective-C. Unfortunately, I am pretty new to Swift, so translating answers is a bit difficult.

What I have so far:

So far, I have declared a circle with MKCircle that looks like,

let location = CLLocationCoordinate2D(latitude: 36.9900,
        longitude: -122.0605)
let circle = MKCircle(centerCoordinate: location, radius: 100)

and I eventually want to use CGPathContainsPoint to detect if an Annotation is inside this circle. The definition for CGPathContainsPoint looks like,

CGPathContainsPoint(_ path: CGPath?, _ m: UnsafePointer<CGAffineTransform>, _ point: CGPoint, _ eoFill: Bool) -> Bool

where,
path - the Path to check the point against
m - An affine transform (not sure what the purpose of this is but most questions have set this param to nil)
point - The point in question
eoFill - use even-odd Fill (true or false, again not sure but most questions have set to false)

My question: How do I convert or translate my MKCircle so that it behaves as a CGPath in order to pass it into CGPathContainsPoint and also convert my CLLocationCoordinate2D to a CGPoint?


Solution

  • Why use a complicated path evaluation to find out if a point is inside a circle? Some variation on what you describe might make sense for testing points against arbitrarily complex regions, but you're talking about a circle. The definition of a circle is the set of points a certain distance (radius) from a chosen point (the center). So:

    1. Create CLLocation objects for both your circle center and your point to be tested.
    2. Use the distanceFromLocation: method to find the distance between them.
    3. If the distance is less than 100 meters (the radius of your circle), the target point is inside the circle. Otherwise it's outside.