MKPolygon - How to determine if a CLLocationCoordinate2D is in a CLLocationCoordinate2D polygon?

前端 未结 5 1012
春和景丽
春和景丽 2021-01-15 06:06

I have the swift code below that draws a polygon and drops an annotation on MKMapView. I am trying to figure out how i could identify if the annotation\'s coordinate is with

5条回答
  •  暖寄归人
    2021-01-15 06:44

    I created a Swift version of the answer by @StefanS and made it easier to read by porting the code from this answer

        func isPoint(point: MKMapPoint, insidePolygon poly: MKPolygon) -> Bool {
    
            let polygonVerticies = poly.points()
            var isInsidePolygon = false
    
            for i in 0.. point.y) || (yp1 <= point.y) && (yp0 > point.y))
                {
                    // If so, get the point where it crosses that line. This is a simple solution
                    // to a linear equation. Note that we can't get a division by zero here -
                    // if yp1 == yp0 then the above if be false.
                    let cross = (xp1 - xp0) * (point.y - yp0) / (yp1 - yp0) + xp0
    
                    // Finally check if it crosses to the left of our test point. You could equally
                    // do right and it should give the same result.
                    if cross < point.x {
                        isInsidePolygon = !isInsidePolygon
                    }
                }
            }
    
            return isInsidePolygon
        }
    

提交回复
热议问题