How to detect taps on MKPolylines/Overlays like Maps.app?

后端 未结 8 871
梦谈多话
梦谈多话 2020-12-23 02:09

When displaying directions on the built-in Maps.app on the iPhone you can \"select\" one of the usually 3 route alternatives that are displayed by tapping on it. I wan\'t to

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 03:09

    Updated for Swift 3

    func isTappedOnPolygon(with tapGesture:UITapGestureRecognizer, on mapView: MKMapView) -> Bool {
        let tappedMapView = tapGesture.view
        let tappedPoint = tapGesture.location(in: tappedMapView)
        let tappedCoordinates = mapView.convert(tappedPoint, toCoordinateFrom: tappedMapView)
        let point:MKMapPoint = MKMapPointForCoordinate(tappedCoordinates)
    
        let overlays = mapView.overlays.filter { o in
            o is MKPolygon
        }
    
        for overlay in overlays {
            let polygonRenderer = MKPolygonRenderer(overlay: overlay)
            let datPoint = polygonRenderer.point(for: point)
            polygonRenderer.invalidatePath()
    
            return polygonRenderer.path.contains(datPoint)
        }
        return false
    }
    

提交回复
热议问题