Home Getting Directions From an Annotation on the Map
Reply: 1

Getting Directions From an Annotation on the Map

kcamp Published in 2017-12-07 22:25:09Z

I am trying to get directions from any annotations that are found on my map. I am using CloudKit as a database to store all my user's information. The annotations use the location index in CloudKit to map out their location on the map. Every time I run my code the annotation comes back as nil, how do I get my code to recognize the location from the annotation and return directions from apple maps?

@IBAction func getDirections(_ sender: Any) {

    let view = MKPointAnnotation().coordinate

    print("Annotation: \(String(describing: view ))")

    let currentLocMapItem = MKMapItem.forCurrentLocation()

    let selectedPlacemark = MKPlacemark(coordinate: view, addressDictionary: nil)
    let selectedMapItem = MKMapItem(placemark: selectedPlacemark)

    let mapItems = [selectedMapItem, currentLocMapItem]

    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]

    MKMapItem.openMaps(with: mapItems, launchOptions:launchOptions)

Rob Reply to 2017-12-08 09:08:59Z

There are two options:

  1. You can use MKDirections to get directions right in your app, without ever going to the Maps app.

  2. You can also pass it off to the Maps app (like your above example) so that the user can then enjoy the full real-time navigation (see traffic, etc.).

But you don’t use the “open in Maps” API to return directions within your app. Use MKDirections for that.

In your code snippet, you are doing:

let view = MKAnnotationView()

That creates an blank annotation view (with no annotation), so obviously if you try to get the annotation for it, it doesn't have one. You presumably want to either

  • save the original annotation that you added to your map view and use that;
  • respond to one of the MKMapViewDelegate methods and use the annotation for that annotation view on your map view; or
  • go back to your original data source from which you originally created the annotation and create a new annotation (not annotation view) from that.

But don't try to create a new, blank annotation view and try to retrieve the annotation view for it, because it won't have one.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.336263 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO