How to open Google Maps to show route using Swift
OK I found the answer myself.
If you want to show directions from the user's current location, leave the field saddr
blank and in the field daddr
you can enter the destination coordinates.
This is how I did it
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
UIApplication.sharedApplication().openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(place.latitude),\(place.longitude)&directionsmode=driving")!)
} else {
NSLog("Can't use comgooglemaps://");
}
}
for any further queries you can refer to this link Google Map URL Scheme
Swift 5 - Code
func openGoogleMap() {
guard let lat = booking?.booking?.pickup_lat, let latDouble = Double(lat) else {Toast.show(message: StringMessages.CurrentLocNotRight);return }
guard let long = booking?.booking?.pickup_long, let longDouble = Double(long) else {Toast.show(message: StringMessages.CurrentLocNotRight);return }
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) { //if phone has an app
if let url = URL(string: "comgooglemaps-x-callback://?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
UIApplication.shared.open(url, options: [:])
}}
else {
//Open in browser
if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
UIApplication.shared.open(urlDestination)
}
}
}
Don't forget to write this in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>comgooglemaps</string>
<string>comgooglemaps-x-callback</string>
</array>
The Answer is already there but in older versions of Swift
In Swift 3
//Working in Swift new versions.
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!))
{
UIApplication.shared.openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(Float(latitude!)),\(Float(longitude!))&directionsmode=driving")! as URL)
} else
{
NSLog("Can't use com.google.maps://");
}