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

后端 未结 8 872
梦谈多话
梦谈多话 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 02:52

    It's an old thread however I found a different way which may help anyone. Tested on multiple routes overlay in Swift 4.2.

     @IBAction func didTapGesture(_ sender: UITapGestureRecognizer) {
            let touchPoint = sender.location(in: mapView)
            let touchCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
            let mapPoint = MKMapPoint(touchCoordinate)
    
            for overlay in mapView.overlays {
                if overlay is MKPolyline {
                    if let polylineRenderer = mapView.renderer(for: overlay) as? MKPolylineRenderer {
                        let polylinePoint = polylineRenderer.point(for: mapPoint)
    
                        if polylineRenderer.path.contains(polylinePoint) {
                            print("polyline was tapped")
                        }
                    }
                }
            }
     }
    

提交回复
热议问题