Opens Apple Maps App from iOS App with Directions

Opens apple maps app from ios app with directions

Here is code to open Map app with directions:

Objective-C Code

NSString* directionsURL = [NSString stringWithFormat:@"http://maps.apple.com/?saddr=%f,%f&daddr=%f,%f",self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, mapPoint.coordinate.latitude, mapPoint.coordinate.longitude];
if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: directionsURL] options:@{} completionHandler:^(BOOL success) {}];
} else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: directionsURL]];
}

with the mapPoint is where you want to direction to.

Swift3 or later

let directionsURL = "http://maps.apple.com/?saddr=35.6813023,139.7640529&daddr=35.4657901,139.6201192"
guard let url = URL(string: directionsURL) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}

Note that saddr, daddr is urlencoded string of location name or location coordinate (about encode URL look at here).

directionsURL example:

// directions with location coordinate
"http://maps.apple.com/?saddr=35.6813023,139.7640529&daddr=35.4657901,139.6201192"
// or directions with location name
"http://maps.apple.com/?saddr=Tokyo&daddr=Yokohama"
// or directions from current location to destination location
"http://maps.apple.com/?saddr=Current%20Location&daddr=Yokohama"

More options parameters (like transport type, map type ...) look at here

Open Apple Maps App With Directions from my ios App iOS 9 Swift 2.2

The following function will open the Apple Maps app and present driving directions from the user's current location to a named destination at a coordinate. The destination name is displayed in the To: field of the Maps app.

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.openInMapsWithLaunchOptions(options)
}

You can call this function from your code as follows:

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

if Control == annotationView.leftCalloutAccessoryView {
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)
}
}

}

How to open Apple Maps directly from app?

General Solution

You should pass app's deeplink as the URL to open them directly. For Maps this is the URL you are looking for:

let mapsURL = URL(string: "maps://q?\(latString),\(longString)")!


Specific Function

Also, there is a Specific function for Maps and that is:

class func openMaps(with mapItems: [MKMapItem], launchOptions: [String : Any]? = nil) -> Bool

You can find out more about this in the documentation



Specific Framework

Also, You can use my framework for this that. supports AppleMaps, GoogleMaps, Waze and Maps.Me.

You can get it from here

How to open Apple Maps driving direction by passing address

Simply use the Apple Maps API. If you can find a business by tiping its name in Apple Maps, you can find it through the APIs. In your case, the correct parameter is daddr, like this:

http://maps.apple.com/?daddr=1+Infinite+Loop,+Cupertino,+CA

You can combine multiple parameters, such as your starting location:

http://maps.apple.com/?saddr=1024+Market+St,+San+Francisco,+CA&daddr=1+Infinite+Loop,+Cupertino,+CA

You can find the list of supported parameters here.

Remember to open the URL via UIApplication.shared().open(url: URL, options: [String: AnyObject], completionHandler: ((Bool) -> Void)?) - in iOS 10 - or UIApplication.shared.open(url: URL)

Open an Alert asking to choose App to open map with

Swift 5+ solution based on previous answers, this one shows a selector between Apple Maps, Google Maps, Waze and City Mapper. It also allows for some optional location title (for those apps that support it) and presents the alert only if there are more than 1 option (it opens automatically if only 1, or does nothing if none).

func openMaps(latitude: Double, longitude: Double, title: String?) {
let application = UIApplication.shared
let coordinate = "\(latitude),\(longitude)"
let encodedTitle = title?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
let handlers = [
("Apple Maps", "http://maps.apple.com/?q=\(encodedTitle)&ll=\(coordinate)"),
("Google Maps", "comgooglemaps://?q=\(coordinate)"),
("Waze", "waze://?ll=\(coordinate)"),
("Citymapper", "citymapper://directions?endcoord=\(coordinate)&endname=\(encodedTitle)")
]
.compactMap { (name, address) in URL(string: address).map { (name, $0) } }
.filter { (_, url) in application.canOpenURL(url) }

guard handlers.count > 1 else {
if let (_, url) = handlers.first {
application.open(url, options: [:])
}
return
}
let alert = UIAlertController(title: R.string.localizable.select_map_app(), message: nil, preferredStyle: .actionSheet)
handlers.forEach { (name, url) in
alert.addAction(UIAlertAction(title: name, style: .default) { _ in
application.open(url, options: [:])
})
}
alert.addAction(UIAlertAction(title: R.string.localizable.cancel(), style: .cancel, handler: nil))
contextProvider.currentViewController.present(alert, animated: true, completion: nil)
}

Note this solution uses R.swift for string localization but you can replace those with NSLocalizedString normally, and it uses a contextProvider.currentViewController to get the presented UIViewController, but you can replace it with self if you are calling this in a view controller already.

As usual, you need to also add the following to your app Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
<string>citymapper</string>
<string>comgooglemaps</string>
<string>waze</string>
</array>

Open Apple Maps programmatically

You can just pass your address information as URL parameters in the URL with which you open the maps app. Say you wanted the maps app to open centered on The White House.

UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/?address=1600,PennsylvaniaAve.,20500")!)

The Maps app opens with the ugly query string in the search field but it shows the right location. Note that the city and state are absent from the search query, it's just the street address and the zip.

A potentially better approach, depending on your needs, would be to get the CLLocation of the address info you have using CLGeocoder.

let geocoder = CLGeocoder()
let str = "1600 Pennsylvania Ave. 20500" // A string of the address info you already have
geocoder.geocodeAddressString(str) { (placemarksOptional, error) -> Void in
if let placemarks = placemarksOptional {
print("placemark| \(placemarks.first)")
if let location = placemarks.first?.location {
let query = "?ll=\(location.coordinate.latitude),\(location.coordinate.longitude)"
let path = "http://maps.apple.com/" + query
if let url = NSURL(string: path) {
UIApplication.sharedApplication().openURL(url)
} else {
// Could not construct url. Handle error.
}
} else {
// Could not get a location from the geocode request. Handle error.
}
} else {
// Didn't get any placemarks. Handle error.
}
}

Open Apple Maps for navigation with destination name set

Try with this function, you only need to pass the coordinates and place name, this works, I use this in several projects

static func openMapsAppWithLocation(coordinates:CLLocationCoordinate2D,placeName:String)
{
let regionDistance:CLLocationDistance = 10000
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 = placeName
mapItem.openInMaps(launchOptions: options)
}

Hope this helps



Related Topics



Leave a reply



Submit