iosswiftxcodemkoverlaymkpolyline

Issue with selecting alternate route in mapkit


I am using MapKit's MKDirection class to get alternate routes in my app, here is my code for showing all routes.

        let directions = MKDirections(request: request)
        
        directions.calculate { response, error in
            if error != nil{
                self.showAlert(message: "Route not found")
                return
            }
            guard let mapRoute = response?.routes.first else {
                return
            }
            for route in response!.routes{
                let newRoute = route
                self.mapView.addOverlay(newRoute.polyline)
                self.mapView.setVisibleMapRect(
                    self.mapView.visibleMapRect.union(
                        newRoute.polyline.boundingMapRect
                    ),
                    edgePadding: UIEdgeInsets(
                        top: 0,
                        left: padding,
                        bottom: padding,
                        right: padding
                    ),
                    animated: true
                )
                self.mapRoutes.append(newRoute)
            }
        }

Have also added tap gesture to map so that we can recognise users intention to select another route, here is the code to convert the touch point and compare it with mapview's overlay.

But for some clicks i am not getting proper route and wrong overlay gets selected.

@objc func isTappedOnPolygon(with tapGesture:UITapGestureRecognizer) {
        let touchPoint = tapGesture.location(in: mapView)
        let touchCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
        let mapPoint = MKMapPoint(touchCoordinate)
        var selectedOverlay:MKPolyline?
        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){
                        selectedOverlay = overlay as? MKPolyline
                        break
                    }
                }
            }
        }
    }

Thanks Arun.


Solution

  • Have you seen this answer yet?

    Try setting a maximum polyLine width: 22px, for any zoom level.

    ā€œ This code detects touches on poly lines with a maximum distance of 22 pixels in every zoom level. Just point your UITapGestureRecognizer to handleTap:ā€

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