在我的应用程序中,我有一个圆周长的坐标数组(CLLocationCoordinate2D)。现在我从某个地方得到一个坐标,我需要检查新坐标是否落在圆圈内。
如果确实如此,我只想在该坐标上显示一个图钉,基本上它应该落在该区域之下。
我应该如何检查这个?
谢谢,
最佳答案
您没有说您的坐标数组是否只是纬度和经度,CLLocationCoordinate2D
结构,或 CLLocation
对象,但如果您创建 CLLocation
对象(如果您还没有),您可以调用 distanceFromLocation
看看它离另一个位置有多远。我假设,除了周长的坐标数组之外,您还有中心的坐标?
如果您有 CLLocationCoordinate2D
,因此您可以这样做:
CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude
longitude:coordinate.longitude];
CLLocation *centerLocation = [[CLLocation alloc] initWithLatitude:centerCoordinate.latitude
longitude:centerCoordinate.longitude];
CLLocationDistance distance = [location distanceFromLocation:centerLocation];
离线与您聊天,听起来 map 上的坐标数组是用户手势的结果(这解释了为什么您没有坐标圆的中心)。
鉴于这种情况,我建议使用 Quartz 方法来测试
CGPoint
在一个 View 中包含在一个封闭的 UIBezierPath
中,我们将从用户的手势构造。因此:
UIBezierPath
当用户在屏幕上拖动手指时; userLocation
map 的属性,将其坐标从 CLLocationCoordinate2D
使用 map View 的 convertCoordinate:toPointToView
查看 View 中的坐标方法)。 CGPoint
在用户当前位置的 map View 中,我们现在可以使用 UIBezierPath
实例方法,containsPoint
测试该点是否在贝塞尔路径内。 因此,这可能看起来像:
- (void)turnOnGestureForView:(MKMapView *)mapView
{
mapView.scrollEnabled = NO;
UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
[mapView addGestureRecognizer:gesture];
}
- (void)turnOffGesture:(UIGestureRecognizer *)gesture map:(MKMapView *)mapView
{
[mapView removeGestureRecognizer:gesture];
mapView.scrollEnabled = YES;
}
- (void)handleGesture:(UIPanGestureRecognizer *)gesture
{
static UIBezierPath *path;
static CAShapeLayer *shapeLayer;
CGPoint location = [gesture locationInView:gesture.view];
if (gesture.state == UIGestureRecognizerStateBegan)
{
if (!shapeLayer)
{
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.lineWidth = 3.0;
[self.mapView.layer addSublayer:shapeLayer];
}
path = [UIBezierPath bezierPath];
[path moveToPoint:location];
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
[path addLineToPoint:location];
shapeLayer.path = [path CGPath];
}
else if (gesture.state == UIGestureRecognizerStateEnded)
{
MKMapView *mapView = (MKMapView *)gesture.view;
[path addLineToPoint:location];
[path closePath];
CGPoint currentLocation = [mapView convertCoordinate:mapView.userLocation.coordinate
toPointToView:gesture.view];
if ([path containsPoint:currentLocation])
NSLog(@"%s path contains %@", __FUNCTION__, NSStringFromCGPoint(currentLocation));
else
NSLog(@"%s path does not contain %@", __FUNCTION__, NSStringFromCGPoint(currentLocation));
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
// if you want to turn off the gesture and turn scrolling back on, you can do that now
[self turnOffGesture:gesture map:mapView];
}
}
关于iphone - 如何检测 GPS 坐标是否落在 MKMapView 上的某个区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654491/