如何使用Swift打开Goog​​le地图以显示路线

sum*_*esh 35 google-maps ios swift

我在互联网上阅读,但找不到合法的答案.当用户点击按钮显示路线时,我需要打开Goog​​le地图.必须自动填写开始和目的地.

我怎样才能在Swift中实现这一目标?

如果有人有解决方案,请提供示例代码.开始始终是用户的当前位置.

sum*_*esh 54

好的,我自己找到了答案.

如果要显示用户当前位置的路线,请将该字段saddr留空,然后在字段daddr中输入目标坐标.

这就是我做到的

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://");
        }
    }
Run Code Online (Sandbox Code Playgroud)

对于任何进一步的查询,您可以参考此链接Google Map URL Scheme


Gur*_*ngh 30

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)
                           }
                }

        }
Run Code Online (Sandbox Code Playgroud)

不要忘记在 info.plist 中写这个

<key>LSApplicationQueriesSchemes</key>
    <array>
    <string>comgooglemaps</string>
    <string>comgooglemaps-x-callback</string>
    </array>
Run Code Online (Sandbox Code Playgroud)

  • info.plist 数据节省了我的时间,谢谢 (3认同)
  • info.plist 也拯救了我们的生命 (2认同)

use*_*635 26

答案已经存在,但在旧版本的Swift中

在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://");
}
Run Code Online (Sandbox Code Playgroud)


Abe*_*eyh 18

对于那些对接受的答案解决方案并没有为他们工作,要添加comgooglemapsLSApplicationQueriesSchemes在info.plist中.

info.plist中


小智 10

@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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Hak*_*çer 8

Swift 4工作代码

if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(location.coordinate.latitude),\(location.coordinate.longitude)&directionsmode=driving") {
        UIApplication.shared.open(url, options: [:])
    }
Run Code Online (Sandbox Code Playgroud)

该代码对我有用。还有呢 没有插入

* LSApplicationQueriesSchemes
Run Code Online (Sandbox Code Playgroud)

如果使用模拟器,则看不到结果。不要忘记在电话上处理您的项目。


kuz*_*zdu 6

我希望用户可以通过浏览器打开谷歌地图(仅当用户没有谷歌地图应用程序时才有效)谷歌在这里提供了相关文档.从iOS 9开始,您必须设置一个方案.你可以在这里找到.

对我来说谷歌解决方案不起作用.也许你更聪明并找到解决方案(请发帖!).

无论如何,我做了一个简单的网络电话:

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)")!)
}
Run Code Online (Sandbox Code Playgroud)

这可以用作sumeshs回答的一种后备.


小智 6

  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)
            }
Run Code Online (Sandbox Code Playgroud)


Har*_*kar 6

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://");
        }
    }
Run Code Online (Sandbox Code Playgroud)

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://");
        }
    }
Run Code Online (Sandbox Code Playgroud)


Cha*_*lva 5

Here is the Swift 3 Update

First, you need to two items to LSApplicationQueriesSchemes in the 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.")
        }
}
Run Code Online (Sandbox Code Playgroud)