我有CLLocation对象,其中包含用户的当前位置,我有一个矩形的每个角可以成角度的4个纬度/长对.现在我想检查CLLocation坐标是否在该矩形内.
以下是矩形的坐标
#define NorthEast_LAT 51.514894
#define NorthEast_LNG -0.135306
#define SouthEast_LAT 51.514831
#define SouthEast_LNG -0.135153
#define NorthWest_LAT 51.514719
#define NorthWest_LNG -0.135858
#define SouthWest_LAT 51.514556
#define SouthWest_LNG -0.135714
Run Code Online (Sandbox Code Playgroud)
我尝试过以下代码,但我认为它只适用于矩形角度为0度的情况.
BOOL withinRect = [delegate.CLController latlngWithInBox:location
point1:CLLocationCoordinate2DMake(NorthEast_LAT, NorthEast_LNG)
point2:CLLocationCoordinate2DMake(SouthEast_LAT, SouthEast_LNG)
point3:CLLocationCoordinate2DMake(NorthWest_LAT, NorthWest_LNG)
point4:CLLocationCoordinate2DMake(SouthWest_LAT, SouthWest_LNG)];
- (BOOL) latlngWithInBox:(CLLocation *)position point1:(CLLocationCoordinate2D)point1 point2:(CLLocationCoordinate2D)point2 point3:(CLLocationCoordinate2D)point3 point4:(CLLocationCoordinate2D)point4 {
if (position.coordinate.latitude >= point3.latitude && position.coordinate.latitude <= point2.latitude
&& position.coordinate.longitude >= point3.longitude && position.coordinate.longitude <= point2.longitude) {
return YES;
}
return NO;
Run Code Online (Sandbox Code Playgroud)
}
确定某个点是否在地图矩形内的另一种方法是使用MKMapKit函数:
MKMapPointForCoordinate - 将坐标转换为地图点 MKMapRectMake - 使用这些点创建rect MKMapRectContainsPoint - 确定指定的地图点是否位于矩形内优点是MKMapKit(MKMapPoint,MKMapRect)使用地图的墨卡托投影,因此您不需要提供球体计算.但是其中一些功能在iOS 4.0及更高版本中可用.
更新:
// 1 ------- 2
// | |
// | x |
// | |
// 3 ------- 4
// 1 = topLeftCorner
// 4 = bottomRightCorner
// x = targetCoordinate
CLLocationCoordinate2D topLeftCorner = /* some coordinate */, bottomRightCorner = /* some coordinate */;
CLLocationCoordinate2D targetCoordinate = /* some coordinate */;
MKMapPoint topLeftPoint = MKMapPointForCoordinate(topLeftCorner);
MKMapPoint bottomRightPoint = MKMapPointForCoordinate(bottomRightCorner);
MKMapRect mapRect = MKMapRectMake(topLeftPoint.x, topLeftPoint.y, bottomRightPoint.x - topLeftPoint.x, bottomRightPoint.y - topLeftPoint.y);
MKMapPoint targetPoint = MKMapPointForCoordinate(targetCoordinate);
BOOL isInside = MKMapRectContainsPoint(mapRect, targetPoint);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2956 次 |
| 最近记录: |