What is the correct URL format to achieve the following:
What doesn't work:
let encoded = "https://www.google.com/maps/dir/?api=1&destination=-20.021999%2C57.579075"
let url = URL(string: encoded)!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
Also, I've tried to encode the URL using addingPercentEncoding
method:
let string = "https://www.google.com/maps/dir/?api=1&destination=\(lat),\(long)"
let encoded = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: encoded)!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
The result in both cases is the same: "Unsupported link - Google Maps can't open this link"
On the other hand, if I delete the Google Maps app, or try the same code in the simulator, everything works fine and I achieve exactly the result I aim for:
Why does the same link successfully launches the "Web" app, but fails to be recognized by the native app?
String in question:https://www.google.com/maps/dir/?api=1&destination=-20.021999,57.579075
The guide I'm following: Google Maps Guide
I've just tried your second approach (with addingPercentEncoding(withAllowedCharacters:)
and provided the given coordinate and got exactly the same error in Google Maps app.
But then I changed coordinate to the one that is in my city and voila! it worked. Seems like google maps simply couldn't generate directions given the (-20.021999, 57.579075) pair. And judging by your second screenshot (with web version presented – it is blank, no map is presented) I think it's struggling with generating directions in your case too. Why does it tell that the link is not supported in such case puzzles me though.
Here's the full code (I've created a blank single-view app):
import UIKit
class ViewController: UIViewController {
override func loadView() {
super.loadView()
let lat = 51.150992
let long = 71.426444
let string = "https://www.google.com/maps/dir/?api=1&destination=\(lat),\(long)"
let encoded = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: encoded)!
UIApplication.shared.open(url)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With