2

I am working on an app that has a list of multiple custom point annotations of places to visit for my partner and I's wedding. I recently figured out how to create a function to open that map. The problem is, when you click on the callout the directions title shows Unknown Location or Nil. I have a title set for all custom point annotations and am just looking for the title of the clicked annotation to be on the map as the end destination title. Any help is much appreciated. This is my first full app and this is the last thing to figure out before getting it up and running. Thanks in advance for your help. Happy to provide more code if the issue isn't coming from this function.

    // Open maps app programatically
func mapView(_ mapView: MKMapView, annotationView view:MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let placemark = MKPlacemark(coordinate: view.annotation!.coordinate, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit]
    view.canShowCallout = true
    self.title = title
    mapItem.name = title
    mapItem.openInMaps(launchOptions: launchOptions)
}
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
Jacquedes
  • 33
  • 5
  • similar! http://stackoverflow.com/questions/43234808/how-to-get-apple-maps-app-not-mapkit-to-add-an-annotation/43243556#43243556 – Fattie Apr 06 '17 at 11:15

1 Answers1

0

So after a ton of research and trying to figure out this problem, I finally found a solution which was a combination of several different answers to some other problems. The following is the solution that worked for me. I hope this helps someone else out there.

    // Open maps app programatically
func openMapsAppWithDirections(to coordinate: CLLocationCoordinate2D, destinationName name: String) {
    let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = name // Provide the name of the destination in the To: field
    mapItem.openInMaps(launchOptions: options)
}

func mapView(_ MapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped Control: UIControl) {

    if Control == annotationView.rightCalloutAccessoryView {
        if let annotation = annotationView.annotation {
            // Unwrap the double-optional annotation.title property or
            // name the destination "Unknown" if the annotation has no title
            let destinationName = (annotation.title ?? nil) ?? "Unknown"
            openMapsAppWithDirections(to: annotation.coordinate, destinationName: destinationName)
        }
    }
}
Jacquedes
  • 33
  • 5