当我在我的应用程序中按下按钮时,我如何能够打开 google 地图?

How would I be able to open google maps when I press a button in my app?

我有这个应用程序,我想在用户按下我的应用程序中的按钮时使用 google 地图或苹果地图打开。我怎么能做到这一点?打开应用程序的地图是否有 link 之类的东西?如果您能指出正确的方向,那将非常有帮助。谢谢!我在下面设置了这样的按钮:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in (touches ) {
    let location = touch.locationInNode(self)
    let node = self.nodeAtPoint(location)

    if node.name == "openMaps" {

     //code to open google maps or apple maps....

    }

使用这个:

if node.name == "openMaps" {
    let customURL = "comgooglemaps://"

    if UIApplication.sharedApplication().canOpenURL(NSURL(string: customURL)) {
        UIApplication.sharedApplication().openURL(NSURL(string: customURL))
    }
    else {
        var alert = UIAlertController(title: "Error", message: "Google maps not installed", preferredStyle: UIAlertControllerStyle.Alert)
        var ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
        alert.addAction(ok)
        self.presentViewController(alert, animated:true, completion: nil)
    }
}

您可以找到有关 google 地图 URL 方案的更多信息 here

编辑:您必须向您的 info.plist 添加密钥才能正常工作。

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>googlechromes</string>
    <string>comgooglemaps</string>
</array>

编辑:根据更新 Google Maps docs 也将 "googlechromes" 添加到上面的 plist。

单击按钮(实际)调用函数 "directions()",代码如下:

func directions() {
    // if GoogleMap installed
    if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
        UIApplication.shared.openURL(NSURL(string:
            "comgooglemaps://?saddr=&daddr=\(Float(event.addressLat)!),\(Float(event.addressLong)!)&directionsmode=driving")! as URL)

    } else {
        // if GoogleMap App is not installed
        UIApplication.shared.openURL(NSURL(string:
            "https://maps.google.com/?q=@\(Float(event.addressLat)!),\(Float(event.addressLong)!)")! as URL)
    }
}

为 LSApplicationQueriesSchemes 编辑您的info.plist:

希望能有所帮助!