ios 如何使用 Swift 打开谷歌地图以显示路线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32039816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open Google Maps to show route using Swift
提问by sumesh
I read around the Internet but couldn't find a legit answer. I need to open Google Maps when the user clicks a button to show directions. Start and destination must be automatically filled.
我在互联网上阅读,但找不到合法的答案。当用户单击按钮以显示路线时,我需要打开 Google 地图。起点和终点必须自动填写。
How can I achieve this in Swift?
我怎样才能在 Swift 中实现这一点?
If anyone has a solution, please provide me with a sample code. The start is always going to be the user's current location.
如果有人有解决方案,请向我提供示例代码。起点始终是用户的当前位置。
回答by sumesh
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.
如果您想显示从用户当前位置出发的路线,请将字段saddr
留空,daddr
您可以在该字段中输入目的地坐标。
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
对于任何进一步的查询,您可以参考此链接Google Map URL Scheme
回答by user3745635
The Answer is already there but in older versions of Swift
答案已经存在,但在旧版本的 Swift 中
In Swift 3
在斯威夫特 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://");
}
回答by Abedalkareem Omreyh
回答by Gurpreet Singh
Swift 5 - Code
Swift 5 - 代码
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
不要忘记在 info.plist 中写这个
<key>LSApplicationQueriesSchemes</key>
<array>
<string>comgooglemaps</string>
<string>comgooglemaps-x-callback</string>
</array>
回答by Anoop
@IBAction func NavigationTrackerPressedPressed(_ sender: UIButton){
if let UrlNavigation = URL.init(string: "comgooglemaps://") {
if UIApplication.shared.canOpenURL(UrlNavigation){
if self.destinationLocation?.longitude != nil && self.destinationLocation?.latitude != nil {
let lat = (self.destinationLocation?.latitude)!
let longi = (self.destinationLocation?.longitude)!
if let urlDestination = URL.init(string: "comgooglemaps://?saddr=&daddr=\(lat),\(longi)&directionsmode=driving") {
UIApplication.shared.openURL(urlDestination)
}
}
}
else {
NSLog("Can't use comgooglemaps://");
self.openTrackerInBrowser()
}
}
else
{
NSLog("Can't use comgooglemaps://");
self.openTrackerInBrowser()
}
}
func openTrackerInBrowser(){
if self.destinationLocation?.longitude != nil && self.destinationLocation?.latitude != nil {
let lat = (self.destinationLocation?.latitude)!
let longi = (self.destinationLocation?.longitude)!
if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(lat),\(longi)&directionsmode=driving") {
UIApplication.shared.openURL(urlDestination)
}
}
}
回答by Haktan Enes Bi?er
Swift 4 Working Code
Swift 4 工作代码
if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(location.coordinate.latitude),\(location.coordinate.longitude)&directionsmode=driving") {
UIApplication.shared.open(url, options: [:])
}
this code works for me. And ? didn't insert
这段代码对我有用。和 ?没有插入
* LSApplicationQueriesSchemes
If you use emulator can't see the results. Don't forget work your project on the Phone.
如果你用模拟器看不到结果。不要忘记在电话上工作您的项目。
回答by Hardik Thakkar
1) Method: You can pass the only destination address current address will be automatically fetched by google map application.
1)方法:您可以传递唯一的目的地地址当前地址将被谷歌地图应用程序自动获取。
let strLat : String = "23.035007"
let strLong : String = "72.529324"
override func viewDidLoad() {
super.viewDidLoad()
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
UIApplication.shared.openURL(URL(string:"comgooglemaps://?saddr=&daddr=\(strLat),\(strLong)&directionsmode=driving")!)
}
else {
print("Can't use comgooglemaps://");
}
}
2) You can pass both start and destination address
2)您可以同时传递起始地址和目标地址
let strLat : String = "23.035007"
let strLong : String = "72.529324"
let strLat1 : String = "23.033331"
let strLong2 : String = "72.524510"
override func viewDidLoad() {
super.viewDidLoad()
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
UIApplication.shared.openURL(URL(string:"comgooglemaps://?saddr=\(strLat),\(strLong)&daddr=\(strLat1),\(strLong2)&directionsmode=driving&zoom=14&views=traffic")!)
}
else {
print("Can't use comgooglemaps://");
}
}
回答by kuzdu
I want the possibility that the user can open Google Maps via browser (only works when user hasn't the Google Maps App) Google gives a documentation for that here. Since iOS 9 you have to set a scheme. This you will find here.
我希望用户可以通过浏览器打开谷歌地图(仅在用户没有谷歌地图应用程序时才有效)谷歌在这里提供了一个文档。从 iOS 9 开始,你必须设置一个方案。您将在此处找到。
For me the google solution doesn't work. Maybe you are smarter and find a solution (please post!).
对我来说,谷歌解决方案不起作用。也许您更聪明并找到了解决方案(请发布!)。
Anyway I made a simple web call:
无论如何,我打了一个简单的网络电话:
let lat = 37.7
let lon = -122.4
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"https://maps.google.com")!))
{
UIApplication.sharedApplication().openURL(NSURL(string:
"https://maps.google.com/?q=@\(lat),\(lon)")!)
}
This could be use as a kind of fallback from sumeshs answer.
这可以用作 sumeshs 答案的一种后备。
回答by Sachin Kishore
let lat = self.upcomingListArr[indexPath.item].latitude!
let long = self.upcomingListArr[indexPath.item].longitude!
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
UIApplication.shared.openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(String(describing: lat)),\(String(describing: long))")! as URL)
} else {
UIApplication.shared.openURL(NSURL(string:
"https://www.google.co.in/maps/dir/?saddr=&daddr=\(String(describing: lat)),\(String(describing: long))")! as URL)
}
回答by Chathuranga Silva
Here is the Swift 3 Update
这是 Swift 3 更新
First, you need to two items to LSApplicationQueriesSchemes
in the info.plist.
首先,您需要LSApplicationQueriesSchemes
在 info.plist 中添加两个项目。
Then you can use this function to load address on Google maps.
然后你可以使用这个函数来加载谷歌地图上的地址。
let primaryContactFullAddress = "No 28/A, Kadalana, Moratuwa, Sri Lanka"
@IBAction func showLocaionOnMaps(_ sender: Any) {
let testURL: NSURL = NSURL(string: "comgooglemaps-x-callback://")!
if UIApplication.shared.canOpenURL(testURL as URL) {
if let address = primaryContactFullAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
let directionsRequest: String = "comgooglemaps-x-callback://" + "?daddr=\(address)" + "&x-success=sourceapp://?resume=true&x-source=AirApp"
let directionsURL: NSURL = NSURL(string: directionsRequest)!
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(directionsURL as URL)) {
application.open(directionsURL as URL, options: [:], completionHandler: nil)
}
}
} else {
NSLog("Can't use comgooglemaps-x-callback:// on this device.")
}
}