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)
.
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
. 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:
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.