简体   繁体   English

使用 CLLocationCoordinate2D 的矩形

[英]Rectangle using CLLocationCoordinate2D

I'd like to know whether I can create a rectangle using a top-left and bottom-right CLLocationCoordinate2D , and afterwards check whether a coordinate is part of this rectangle by checking (topLeftCoordinate.latitude < coordinate.latitude && bottomRightCoordinate.latitude > coordinate.latitude) && (topLeftCoordinate.longitude < coordinate.longitude && bottomRightCoordinate.longitude > coordinate.longitude) .我想知道我是否可以使用左上角和右下角CLLocationCoordinate2D创建一个矩形,然后通过检查(topLeftCoordinate.latitude < coordinate.latitude && bottomRightCoordinate.latitude > coordinate.latitude) && (topLeftCoordinate.longitude < coordinate.longitude && bottomRightCoordinate.longitude > coordinate.longitude)

I thought a coordinate would represent a point on a sphere, and then this wouldn't work.我认为坐标将代表球体上的一个点,然后这行不通。 But I get confused due to the 2D at the end of CLLocationCoordinate2D .但是由于CLLocationCoordinate2D末尾的2D ,我感到困惑。 Can someone clarify this?有人可以澄清这一点吗?

Thanks :)谢谢 :)

You will be able to create a MKPolygon from your coordinates and use this function to determine whether a coordinate is inside that polygon:您将能够从您的坐标创建一个 MKPolygon 并使用此函数来确定坐标是否在该多边形内:

func isPoint(point: MKMapPoint, insidePolygon poly: MKPolygon) -> Bool {

    let polygonVerticies = poly.points()
    var isInsidePolygon = false

    for i in 0..<poly.pointCount {
        let vertex = polygonVerticies[i]
        let nextVertex = polygonVerticies[(i + 1) % poly.pointCount]

        // The vertices of the edge we are checking.
        let xp0 = vertex.x
        let yp0 = vertex.y
        let xp1 = nextVertex.x
        let yp1 = nextVertex.y

        if ((yp0 <= point.y) && (yp1 > 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM