ios - 如何检测像 Maps.app 这样的 MKPolylines/Overlays 上的点击?

标签 ios objective-c mkmapview mkoverlay mkpolyline

当在 iPhone 的内置 Maps.app 上显示路线时,您可以通过点击来“选择”通常显示的 3 条备选路线之一。我不想复制此功能并检查水龙头是否位于给定的 MKPolyline 内。

目前我检测到 MapView 上的点击是这样的:

// Add Gesture Recognizer to MapView to detect taps
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleMapTap:)];

// we require all gesture recognizer except other single-tap gesture recognizers to fail
for (UIGestureRecognizer *gesture in self.gestureRecognizers) {
    if ([gesture isKindOfClass:[UITapGestureRecognizer class]]) {
        UITapGestureRecognizer *systemTap = (UITapGestureRecognizer *)gesture;

        if (systemTap.numberOfTapsRequired > 1) {
            [tap requireGestureRecognizerToFail:systemTap];
        }
    } else {
        [tap requireGestureRecognizerToFail:gesture];
    }
}

[self addGestureRecognizer:tap];

我按如下方式处理水龙头:

- (void)handleMapTap:(UITapGestureRecognizer *)tap {
    if ((tap.state & UIGestureRecognizerStateRecognized) == UIGestureRecognizerStateRecognized) {
        // Check if the overlay got tapped
        if (overlayView != nil) {
            // Get view frame rect in the mapView's coordinate system
            CGRect viewFrameInMapView = [overlayView.superview convertRect:overlayView.frame toView:self];
            // Get touch point in the mapView's coordinate system
            CGPoint point = [tap locationInView:self];

            // Check if the touch is within the view bounds
            if (CGRectContainsPoint(viewFrameInMapView, point)) {
                [overlayView handleTapAtPoint:[tap locationInView:self.directionsOverlayView]];
            }
        }
    }
}

这按预期工作,现在我需要检查点击是否位于给定的 MKPolyline overlayView 内(不严格,我的用户点击折线附近的某处,这应该作为点击处理)。

执行此操作的好方法是什么?

- (void)handleTapAtPoint:(CGPoint)point {
    MKPolyline *polyline = self.polyline;

    // TODO: detect if point lies withing polyline with some margin
}

谢谢!

最佳答案

这个问题比较老,但我的回答可能对其他正在寻找此问题解决方案的人有用。

此代码检测在每个缩放级别中最大距离为 22 像素的多边形线上的触摸。只需将您的 UITapGestureRecognizer 指向 handleTap:

/** Returns the distance of |pt| to |poly| in meters
 *
 * from http://paulbourke.net/geometry/pointlineplane/DistancePoint.java
 *
 */
- (double)distanceOfPoint:(MKMapPoint)pt toPoly:(MKPolyline *)poly
{
    double distance = MAXFLOAT;
    for (int n = 0; n < poly.pointCount - 1; n++) {

        MKMapPoint ptA = poly.points[n];
        MKMapPoint ptB = poly.points[n + 1];

        double xDelta = ptB.x - ptA.x;
        double yDelta = ptB.y - ptA.y;

        if (xDelta == 0.0 && yDelta == 0.0) {

            // Points must not be equal
            continue;
        }

        double u = ((pt.x - ptA.x) * xDelta + (pt.y - ptA.y) * yDelta) / (xDelta * xDelta + yDelta * yDelta);
        MKMapPoint ptClosest;
        if (u < 0.0) {

            ptClosest = ptA;
        }
        else if (u > 1.0) {

            ptClosest = ptB;
        }
        else {

            ptClosest = MKMapPointMake(ptA.x + u * xDelta, ptA.y + u * yDelta);
        }

        distance = MIN(distance, MKMetersBetweenMapPoints(ptClosest, pt));
    }

    return distance;
}


/** Converts |px| to meters at location |pt| */
- (double)metersFromPixel:(NSUInteger)px atPoint:(CGPoint)pt
{
    CGPoint ptB = CGPointMake(pt.x + px, pt.y);

    CLLocationCoordinate2D coordA = [mapView convertPoint:pt toCoordinateFromView:mapView];
    CLLocationCoordinate2D coordB = [mapView convertPoint:ptB toCoordinateFromView:mapView];

    return MKMetersBetweenMapPoints(MKMapPointForCoordinate(coordA), MKMapPointForCoordinate(coordB));
}


#define MAX_DISTANCE_PX 22.0f
- (void)handleTap:(UITapGestureRecognizer *)tap
{
    if ((tap.state & UIGestureRecognizerStateRecognized) == UIGestureRecognizerStateRecognized) {

        // Get map coordinate from touch point
        CGPoint touchPt = [tap locationInView:mapView];
        CLLocationCoordinate2D coord = [mapView convertPoint:touchPt toCoordinateFromView:mapView];

        double maxMeters = [self metersFromPixel:MAX_DISTANCE_PX atPoint:touchPt];

        float nearestDistance = MAXFLOAT;
        MKPolyline *nearestPoly = nil;

        // for every overlay ...
        for (id <MKOverlay> overlay in mapView.overlays) {

            // .. if MKPolyline ...
            if ([overlay isKindOfClass:[MKPolyline class]]) {

                // ... get the distance ...
                float distance = [self distanceOfPoint:MKMapPointForCoordinate(coord)
                                                toPoly:overlay];

                // ... and find the nearest one
                if (distance < nearestDistance) {

                    nearestDistance = distance;
                    nearestPoly = overlay;
                }
            }
        }

        if (nearestDistance <= maxMeters) {

            NSLog(@"Touched poly: %@\n"
                   "    distance: %f", nearestPoly, nearestDistance);
        }
    }
}

关于ios - 如何检测像 Maps.app 这样的 MKPolylines/Overlays 上的点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11713788/

相关文章:

ios - 以预定义格式将 NSDictionary 转换为 NSString 并转换回来

ios - 文件循环 : read file into NSString, 那就是 id 是文件名(没有.txt)

ios - WKWebView在后台,几个奇怪的断言

ios - viewWillDisappear 和 viewDidDissapear 之间的延迟

ios - gpus_ReturnNotPermittedKillClient 应用后台运行时 MKMapView 抛出错误

ios - iphone 6 的编译错误(没有要编译的架构)

ios - SwiftUI HStack slider 不出现

ios - 如何从包含我的 UIViewController 的 UITableViewController 中显示新 View ?

ios - 为 segue 做准备 - 只是不要做对

ios - 使用 GPS 坐标在 iOs map 上创建折线