当我在应用程序中按下按钮时,如何才能打开谷歌地图?

时间:2015-09-24 23:52:07

标签: ios xcode swift google-maps apple-maps

我有这个应用程序,当用户按下我的应用程序中的按钮时,我想使用谷歌地图或苹果地图打开。我怎么能这样做?有没有像打开应用程序的地图的链接或其他东西?如果你能指出我正确的方向,那将是非常有帮助的。谢谢!我按下这个按钮设置如下:

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....

    }

2 个答案:

答案 0 :(得分:60)

使用此:

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地图网址计划here

的更多信息

修改:您必须为info.plist添加密钥才能生效。

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

修改:每次更新的Google Maps docs都会将“googlechromes”添加到上面。

答案 1 :(得分:6)

点击按钮(在操作中)使用以下代码调用“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:

enter image description here

希望会有所帮助!