我正在根据路线绘制叠加层。我从路线a到路线b,然后路线b到路线c。
我想检测是否在mkoverlay上的任何地方点按了叠加层。
我使用了这个例子Detecting touches on MKOverlay in iOS7 (MKOverlayRenderer)
并将其转换为swift。
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
if touch.tapCount == 1 {
let touchLocation = touch.location(in: self)
let locationCoordinate = self.convert(touchLocation, toCoordinateFrom: self)
let mapPoint: MKMapPoint = MKMapPointForCoordinate(locationCoordinate)
let mapPointAsCGP = CGPoint(x: CGFloat(mapPoint.x), y: CGFloat(mapPoint.y))
for overlay: MKOverlay in self.overlays {
if (overlay is MKPolygon) {
let polygon: MKPolygon? = (overlay as? MKPolygon)
let mpr: CGMutablePath = CGMutablePath()
let polygonPoints = polygon?.points
let polygonPointCount = Int((polygon?.pointCount)!)
for p in 0..<polygonPointCount {
let mp: MKMapPoint = polygonPoints.unsafelyUnwrapped()[polygonPointCount]
if p == 0 {
mpr.move(to: CGPoint(x: CGFloat(mp.x), y: CGFloat(mp.y)), transform: .identity)
}
else {
mpr.addLine(to: CGPoint(x: CGFloat(mp.x), y: CGFloat(mp.y)), transform: .identity)
}
}
if mpr.contains(mapPointAsCGP, using: .winding, transform: .identity) {
print("test")
}
}
}
}
}
super.touchesEnded(touches, with: event)
}
我不确定为什么他们在那里有if语句
if (overlay is MKPolygon)
因为它永远不会被调用,因为它是一个mkoverlay数组。
答案 0 :(得分:3)
我发现这样做比依靠触摸事件方法要好得多。
关于以下问题:
if (overlay is MKPolygon)
我们需要将叠加层转换为多边形,以便我们可以访问 点数组,并重建路径。虽然在我的方法下面, 你只需要访问点数组就是renderer.path 零。因为我正在使用目前正在使用的叠加层 地图,我确信路径不是零。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tap = UITapGestureRecognizer(target: self, action: #selector(mapTapped(_:)))
self.map.addGestureRecognizer(tap)
}
func mapTapped(_ gesture: UITapGestureRecognizer){
let point = gesture.location(in: self.map)
let coordinate = self.map.convert(point, toCoordinateFrom: nil)
let mappoint = MKMapPointForCoordinate(coordinate)
for overlay in self.map.overlays {
if let polygon = overlay as? MKPolygon {
guard let renderer = self.map.renderer(for: polygon) as? MKPolygonRenderer else { continue }
let tapPoint = renderer.point(for: mappoint)
if renderer.path.contains(tapPoint) {
print("Tap was inside this polygon")
break // If you have overlapping overlays then you'll need an array of overlays which the touch is in, so remove this line.
}
continue
}
if let circle = overlay as? MKCircle {
let centerMP = MKMapPointForCoordinate(circle.coordinate)
let distance = MKMetersBetweenMapPoints(mappoint, centerMP) // distance between the touch point and the center of the circle
if distance <= circle.radius {
print("Tap was inside this circle")
break // If you have overlapping overlays then you'll need an array of overlays which the touch is in, so remove this line.
}
continue
}
}
}