您可以从矩形的四个点创建一个路径,然后使用CGPathContainsPoint 检查当前位置是否在路径内。
至于经纬度到平面x、y坐标的转换,最简单的解决方案是使用Map Kit使用墨卡托投影。更多信息请查看Understanding Map Geometry。
这是一个例子:
// create four rectangle points from A, B
dx = (B.x - A.x) * 0.05; // 5% of the A-B length
dy = (B.y - A.y) * 0.05;
// topmost corner, above B
points[0].x = B.x + dx - dy;
points[0].y = B.y + dy + dx;
//rightmost corner, to the right from B
points[1].x = B.x + dx + dy;
points[1].y = B.y + dy - dx;
...
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, points[0].x, points[0].y);
CGPathAddLineToPoint(path, NULL, points[1].x, points[1].y);
CGPathAddLineToPoint(path, NULL, points[2].x, points[2].y);
CGPathAddLineToPoint(path, NULL, points[3].x, points[3].y);
CGPathCloseSubpath(path);
// convert latitude, longitude to planar coordinates
MKMapPoint location = MKMapPointForCoordinate([newLocation coordinate]);
BOOL inside = CGPathContainsPoint(path, NULL, CGPointMake(location.x, location.y), YES);
CGPathRelease(path);
注意:此代码期望当前位置是一个点,而实际上,它是一个点和一个精度半径,实际上是一个圆。这使事情变得有点复杂,因为现在您需要定义如何处理当前位置不知道确切但您只知道它在圆圈中某处的情况。如果矩形很大(比如 5 公里),那么您可能只需要小于 50 米的精度半径,就好像当前位置是精确的一样进行计算,而忽略计算的微小误差。如果矩形更小(比如 50m),您也可以像当前位置一样进行计算,但是误报概率会更高(例如,有时您会被检测为在矩形中,而您会站在外面)。
或者您可能想寻求“完美”解决方案并进行圆矩形相交,这更复杂,不仅可能导致“是”和“否”答案,而且“以这种准确性无法确定您是否是矩形内部或外部”。