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

时间:2015-08-16 20:50:53

标签: ios swift google-maps

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

如何在Swift中实现这一目标?

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

19 个答案:

答案 0 :(得分:46)

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

如果您想显示用户当前位置的路线,请将字段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://");
        }
    }

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

答案 1 :(得分:23)

答案已经存在,但在旧版本的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://");
}

答案 2 :(得分:14)

对于那些已接受答案的解决方案并不适合他们的人,请记得在info.plist中将comgooglemaps添加到LSApplicationQueriesSchemes

info.plist

答案 3 :(得分:8)

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

答案 4 :(得分:6)

我希望用户可以通过浏览器打开Goog​​le地图(仅当用户没有使用Google地图应用时才有效) Google为here提供了文档。 从iOS 9开始,您必须设置一个方案。您会看到here

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

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

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

这可以作为sumeshs回答的一种回退。

答案 5 :(得分:6)

Swift 4工作代码

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

此代码对我有用。而且我没有插入

* LSApplicationQueriesSchemes

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

答案 6 :(得分: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)
            }

答案 7 :(得分:5)

1)方法:您可以传递唯一的目标地址,当前地址将由谷歌地图应用程序自动获取。

<configuration>
  <property>
    <name>hbase.cluster.distributed</name>
    <value>true</value>
  </property>
  <property>
    <name>hbase.rootdir</name>
    <value>hdfs://001/hbase</value>
  </property>
  <property>
    <name>hbase.zookeeper.quorum</name>
    <value>zk1:2181,zk2:2181,zk3:2181</value>
  </property>
</configuration>

2)您可以传递开始和目的地地址

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://");
        }
    }

答案 8 :(得分:4)

这是Swift 3更新

首先,您需要在info.plist中将两个项目LSApplicationQueriesSchemes

enter image description here

然后您可以使用此功能在Google地图上加载地址。

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

答案 9 :(得分:2)

您可以为URL创建小型构建器,该构建器会将您重定向到GoogleMaps

/*

 add to InfoPlist:

       <key>LSApplicationQueriesSchemes</key>
        <array>
          <string>comgooglemaps</string>
          <string>comgooglemaps-x-callback</string>
        </array>
 */
final public class GoogleMapsURIConstructor {

  public enum NavigationType: String {

    case driving
    case transit
    case walking
  }

  public class func prepareURIFor(latitude lat: Double,
                                  longitude long: Double,
                                  fromLatitude fromLat: Double? = nil,
                                  fromLongitude fromLong: Double? = nil,
                                  navigation navigateBy: NavigationType) -> URL? {
    if let googleMapsRedirect = URL(string: "comgooglemaps://"),
      UIApplication.shared.canOpenURL(googleMapsRedirect) {

      if let fromLat = fromLat,
        let fromLong = fromLong {

        let urlDestination = URL(string: "comgooglemaps-x-callback://?saddr=\(fromLat),\(fromLong)?saddr=&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination

      } else {

        let urlDestination = URL(string: "comgooglemaps-x-callback://?daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination
      }
    } else {
      if let fromLat = fromLat,
        let fromLong = fromLong {

        let urlDestination = URL(string: "https://www.google.co.in/maps/dir/?saddr=\(fromLat),\(fromLong)&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination

      } else {

        let urlDestination = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination
      }
    }
  }
}

用法:

  let uri = GoogleMapsURIConstructor.prepareURIFor(latitude: lat,
                                                   longitude: long,
                                                   fromLatitude: userLatitude,
                                                   fromLongitude: userLongitude,
                                                   navigation: .driving)
   UIApplication.shared.open(uri, options: [: ], completionHandler: nil)

结果:

enter image description here

答案 10 :(得分:1)

我们可以使用此方法打开Goog​​le地图。如果未安装谷歌地图,它将重定向到浏览器。

    func redirectToGoogleMap(coordinates : String) {

       if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(coordinates)&directionsmode=driving"),
           UIApplication.shared.canOpenURL(url) {
           print("comgoogle maps worked")
           if #available(iOS 10, *) {
               UIApplication.shared.open(url, options: [:], completionHandler:nil)
           } else {
               UIApplication.shared.openURL(url)
           }
       } else{
        if let url = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(coordinates)&directionsmode=driving"),
            UIApplication.shared.canOpenURL(url) {
             print("google com maps worked")
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:], completionHandler:nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }else{

           kSweetAlert.showAlert(CommonMethods.setLangText("oops"), subTitle: "Oops! Could not open google maps", style: AlertStyle.error)
        }
       }
   }`

答案 11 :(得分:1)

如果未安装Google Map应用,请使用Apple Map版本打开。

import Foundation
import CoreLocation
import UIKit
import MapKit

struct GoogleMapApp {
    func openWithDirection(cordinate: CLLocationCoordinate2D, locationName: String) {
        let hasGoogleMapApp = UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!)

        if hasGoogleMapApp {
            let urlString = "comgooglemaps-x-callback://?saddr=&daddr=\(cordinate.latitude),\(cordinate.longitude)&directionsmode=driving"
            if let url = URL(string: urlString) {
                UIApplication.shared.open(url, options: [:])
            }
        } else {
            // If google map not installed, open with Apple Map App
            let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: cordinate, addressDictionary: nil))
            mapItem.name = locationName
            mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
        }
    }
}

答案 12 :(得分:0)

//我希望它能有效地发挥作用。

let googleURL = NSURL(string: "comgooglemaps://?q=")

if(UIApplication.shared.canOpenURL(googleURL! as URL)) {
     UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=\(DEVICE_LAT),\(DEVICE_LONG)&daddr=\(addressLat),\(addressLng)&directionsmode=driving")!, options: [:], completionHandler: nil)
}

//还可以根据附图设置来自info.plist的权限。

enter image description here

答案 13 :(得分:0)

首先,谢谢你们提供的其他答案。但是当我在工作时,找不到适合我的答案。结果,我制作了两种情况的工作代码:用户拥有google maps应用程序,如果没有。 这是我的代码版本。 Xcode 10,Swift 4.2。希望对您有所帮助。

步骤1:查找您的info.plist并打开为->源代码

First you should find your info.plist and open it as Source Code.

步骤2:<dict></dict>

之间添加这些行

enter image description here

第3步:在您的操作中添加此代码。不要忘记设置纬度和经度。

        let latitude = 44.987781
        let longitude = 88.987781
        let appDomen: String = "comgooglemaps://"
        let browserDomen: String = "https://www.google.co.in/maps/dir/"
        let directionBody: String = "?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving"

        // Make route with google maps application
        if let appUrl = URL(string: appDomen), UIApplication.shared.canOpenURL(appUrl) {
            guard let appFullPathUrl = URL(string: appDomen + directionBody) else { return }
            UIApplication.shared.openURL(appFullPathUrl)

        // If user don't have an application make route in browser
        } else if let browserUrl = URL(string: browserDomen), UIApplication.shared.canOpenURL(browserUrl) {
            guard let browserFullPathUrl = URL(string: browserDomen + directionBody) else { return }
            UIApplication.shared.openURL(browserFullPathUrl)
        }

答案 14 :(得分:0)

在Swift 4中:

 if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
       UIApplication.shared.open((NSURL(string:
            "comgooglemaps://?saddr=&daddr=\(trashDictionarySorted[indexPath.section][0])&directionsmode=driving")! as URL), options: [:], completionHandler: nil)

        } else {
            NSLog("Can't use comgooglemaps://");
        }
    }

答案 15 :(得分:0)

答案已经存在,但在较早版本的Swift中,如果您的iPhone未安装Google Map Application,则此代码可以在浏览器中打开Goog​​le Map。

在Swift 4中

import MapKit

func openGoogleDirectionMap(_ destinationLat: String, _ destinationLng: String) {

    let LocationManager = CLLocationManager()

    if let myLat = LocationManager.location?.coordinate.latitude, let myLng = LocationManager.location?.coordinate.longitude {

        if let tempURL = URL(string: "comgooglemaps://?saddr=&daddr=\(destinationLat),\(destinationLng)&directionsmode=driving") {

            UIApplication.shared.open(tempURL, options: [:], completionHandler: { (isSuccess) in

                if !isSuccess {

                    if UIApplication.shared.canOpenURL(URL(string: "https://www.google.co.th/maps/dir///")!) {

                        UIApplication.shared.open(URL(string: "https://www.google.co.th/maps/dir/\(myLat),\(myLng)/\(destinationLat),\(destinationLng)/")!, options: [:], completionHandler: nil)

                    } else {

                         print("Can't open URL.")

                    }

                }

            })

        } else {

            print("Can't open GoogleMap Application.")

        }

    } else {

        print("Prease allow permission.")

    }

}

答案 16 :(得分:0)

func openTrackerInBrowser(lat: String, long: String, dlat: String, dlong: String){

    if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=\(lat),\(long)&daddr=\(dlat),\(dlong)&directionsmode=driving") {
        UIApplication.shared.open(urlDestination, options: [:], completionHandler: nil)

    }
}

答案 17 :(得分:0)

快捷键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)
                           }
                }

        }

不要忘记将其写在info.plist

<key>LSApplicationQueriesSchemes</key>
    <array>
    <string>comgooglemaps</string>
    <string>comgooglemaps-x-callback</string>
    </array>

答案 18 :(得分:0)

SWIFT 5.1(适用于我)

// Destination Address (Lat/Long)
let place = business?.businessAddresse
// Google URL
let stringURL = "comgooglemaps://"
// Checking Nil
if !(place?.latitude == nil) || !(place?.longitude == nil) {
  if UIApplication.shared.canOpenURL(URL(string: stringURL)!) {
    // If have Google Map App Installed
    if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(place?.latitude ?? 0.0),\(place?.longitude ?? 0.0)&directionsmode=driving") {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
  } else {
    // If have no Google Map App (Run Browser Instead)
    if let destinationURL = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(place?.latitude ?? 0.0),\(place?.longitude ?? 0.0)&directionsmode=driving") {
      UIApplication.shared.open(destinationURL, options: [:], completionHandler: nil)
    }
  }
} else {
  // Show Alert When No Location Found
  self.delegate?.noDirectionError(title: "Error", message: "There's no direction available for this restaurant")
}

注意:该代码仅适用于iOS 11或更高版本,希望也能对您有所帮助。