Search code examples
swiftmapkitswiftuimapkitannotation

Trigger NavigationLink through tap on Annotation in Mapkit


I would like to trigger a NavigationLink through a tap on a Annotation in Mapkit. I am able to set a bool, that a certain annotation was tapped, but i never was able to call a SwiftUI View through it.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            guard !(annotation is MKUserLocation) else {
                return nil
            }

            let identifier = "Annotation"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

            if annotationView == nil {
                annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)

                annotationView?.canShowCallout = true

                annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            } else {
                annotationView?.annotation = annotation
            }

            return annotationView
        }

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
            let selectedAssistance = self.parent.assistances.first {
                    $0.location.location?.coordinate == view.annotation?.coordinate
            }

            guard selectedAssistance != nil else {
                return
            }

            self.parent.selectedAssistance = selectedAssistance?.serverId ?? ""
            self.parent.presentSheet = true
        }

Solution

  • I made it, by calling my own MapView in a ZStack, and placed a NavLink behind it, which is active on a Binding