MKPolyline检测自相交线OBJECTIVE C.

时间:2016-11-22 01:48:28

标签: ios objective-c mkpolyline

如何检测MKPolyline是否与自身相交?我试过研究这个,但只发现有两行或更多行的问题。如何检测我是否只有一行/一笔?我希望在用户释放触摸后检测到它。

我目前在touchEnded函数中有此代码。

            CGPoint location = [touch locationInView:self.mapView];
            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.mapView];
            [self.coordinates addObject:[NSValue valueWithMKCoordinate:coordinate]];
            NSInteger numberOfPoints = [self.coordinates count];

            if(numberOfPoints > 2)
            {
                [self setLineLength:[self getLengthArea]];
                if([self lineLength] < 401)
                {
                    if (numberOfPoints > 2)
                    {
                        CLLocationCoordinate2D points[numberOfPoints];
                        for (NSInteger i = 0; i < numberOfPoints; i++) {
                            points[i] = [self.coordinates[i] MKCoordinateValue];
                        }
                        [self.mapView addOverlay:[MKPolyline polylineWithCoordinates:points count:numberOfPoints]];
                    }

                    PCAnnotation *ann = [[PCAnnotation alloc] init];
                    [ann setCoordinate:coordinate];
                    ann.title = @"End";
                    [self.mapView addAnnotation:ann];
                }
                else
                {
                    NSArray *overlayItems = [self.mapView overlays];
                    NSArray *annotations = [self.mapView annotations];
                    [self.mapView removeOverlays:overlayItems];
                    [self.mapView removeAnnotations:annotations];
                }

            }

1 个答案:

答案 0 :(得分:5)

MKPolyline继承了MKMultiPoint格式 它有一个- (MKMapPoint *)points;方法,

您可以尝试检查所有线段之间的交叉点。

“这些点按照提供的顺序端到端连接。”

所以你可以在每两个点之间创建自己的线段, 并且在有一系列线段后,您可以检查它们的交叉点。

这是一个用于检查交叉点的C ++代码段: 它可以很容易地翻译成Objective-C和其他任何东西。

public static bool LineSegmentsCross(Vector2 a, Vector2 b, Vector2 c,     Vector2 d)
{
     float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));

     if (denominator == 0)
     {
          return false;
     }

     float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));

     float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));

     if (numerator1 == 0 || numerator2 == 0)
     {
          return false;
     }

     float r = numerator1 / denominator;
     float s = numerator2 / denominator;

     return (r > 0 && r < 1) && (s > 0 && s < 1);
}