Lory Lory Lory Lory - 28 days ago 14
Swift Question

How to launch Maps app and start navigation

In my iOS app I have latitude and longitude (

CLLocationCoordinate2D
) of a place the user would like to reach. I want than, when the relative button is pressed, that Maps application is launched and that street navigation to that place is started too. How can I achieve that? My code up to now is:

@IBAction func launchMapsApp(sender:UIButton) {
if (sender == self.navButton) {

let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: self.currentCoordinates, addressDictionary: nil))

mapItem.name = ""

//You could also choose: MKLaunchOptionsDirectionsModeWalking
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey: true]

mapItem.openInMapsWithLaunchOptions(launchOptions as? [String : AnyObject])
}

}


But with this the Maps app is simply launched and I simply see a map of my state (Italy) and nothing more happens. Maybe, because I have run in only in simulator?
Thanks to all

Answer

You were on the right track: This is my swift 2.0 code:

let latitude:CLLocationDegrees = xx.xxxxx
let longitude: CLLocationDegrees = xx.xxxxx
let regiondistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionspan  = MKCoordinateRegionMakeWithDistance(coordinates, regiondistance, regiondistance)
let options = MKLaunchOptionsMapCenterKey:NSValue(MKCoordinate:regionspan.center),MKLaunchOptionsMapSpanKey:NSValue(MKCoordinateSpan:regionspan.span)]

let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapitem = MKMapItem(placemark: placemark)
mapitem.name = "Name you want"
mapitem.openInMapsWithLaunchOptions(options)

I hope my code gives you some insight.

Comments