1

我一直在尝试确定点击手势是否在覆盖多边形中,但无济于事。

我正在尝试制作国家叠加地图 - 单击叠加时我希望能够知道叠加的国家/地区。

首先我发现了这个:Detecting touches on MKOverlay in iOS7 (MKOverlayRenderer)和这个:detect if a point is inside a MKPolygon overlay这表明:

  1. 在您的触摸点周围制作一个小矩形,看看它是否与任何叠加层相交。

```

           //point clicked
           let point = MKMapPointForCoordinate(newCoordinates)

           //make a rectangle around this click
           let mapRect = MKMapRectMake(point.x, point.y, 0,0);

           //loop through the polygons on the map and 
           for polygon in worldMap.overlays as! [MKPolygon] {
              if polygon.intersectsMapRect(mapRect) {
                 print("found intersection")
              }
           }

```

  1. 但是,现在已弃用viewForOverlay与有前途的探测功能一起使用。CGPathContainsPointviewForOverlay

这导致我发现Detecting a point in a MKPolygon break with iOS7 (CGPathContainsPoint)建议采用以下方法:

  1. 从每个叠加层的点制作一个可变多边形(而不是使用 deprecated viewForOverlay),然后CGPathContainsPoint如果单击的点在叠加层中,则使用返回。但是我无法使这段代码工作。

```

func overlaySelected (gestureRecognizer: UIGestureRecognizer) {
    let pointTapped = gestureRecognizer.locationInView(worldMap)
    let newCoordinates = worldMap.convertPoint(pointTapped, toCoordinateFromView: worldMap)
    let mapPointAsCGP = CGPointMake(CGFloat(newCoordinates.latitude), CGFloat(newCoordinates.longitude));

    print(mapPointAsCGP.x, mapPointAsCGP.y)    

    for overlay: MKOverlay in worldMap.overlays {
        if (overlay is MKPolygon) {
            let polygon: MKPolygon = (overlay as! MKPolygon)
            let mpr: CGMutablePathRef = CGPathCreateMutable()

            for p in 0..<polygon.pointCount {
                let mp = polygon.points()[p]
                print(polygon.coordinate)
                if p == 0 {
                    CGPathMoveToPoint(mpr, nil, CGFloat(mp.x), CGFloat(mp.y))
                }
                else {
                    CGPathAddLineToPoint(mpr, nil, CGFloat(mp.x), CGFloat(mp.y))
                }
            }

            if CGPathContainsPoint(mpr, nil, mapPointAsCGP, false) {
                print("------ is inside! ------")
            }

        }
    }
}

```

第一种方法有效,但无论我尝试使点击点周围矩形的高度和宽度有多小,点击let mapRect = MKMapRectMake(point.x, point.y, 0.00000000001,0.00000000001);的准确性都不可靠,因此您最终可以一次点击多个多边形。

目前我正在通过使用“MKPolygon”属性来决定哪个县更靠近水龙头coordinate——它给出了多边形的中心点。有了这个,就可以测量从这个多边形到点击点的距离,以找到最近的那个。但这并不理想,因为用户可能永远无法访问他们想要访问的国家/地区。

所以,总结一下我的问题:

  1. CGPathContainsPoint在上面的第二种方法(一种使用)中,我没有正确实现某些东西吗?
  2. 有没有更准确的方法来使用矩形方法注册点击事件?
  3. 有关如何实现单击地图并查看单击是否在叠加层上的目标的任何其他建议或指示。
4

0 回答 0