当我在我的应用程序中按下一个按钮时,我该如何打开谷歌地图?

19

我有一个应用程序,希望在用户按下按钮时使用谷歌地图或苹果地图打开。我该如何实现呢?是否有像链接一样可以打开地图的方式,还是需要其他方法?如果您能指导一下方向,那将非常有帮助。谢谢!我已经设置了以下按钮:

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个回答

65

使用这个:

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 Maps URL方案的更多信息。

编辑:为使其起作用,您必须将密钥添加到info.plist中。

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

编辑:根据更新的Google Maps文档,在上面的plist中也添加了“googlechromes”。


11
这无法在iOS9上运行。你可能会收到以下警告:“该应用程序不允许查询方案comgooglemaps”。你还需要列出你的方案LSApplicationQueriesSchemes。 - Leo Dabus
有没有其他的方法可以代替? - coding22
我收到了@LeoDabus的错误提示,有没有其他方法可以避免这个错误。 - coding22
我查了一下,它说你必须在Xcode的info.plist文件中将其加入白名单。我该怎么做呢? - coding22
@coding22 编辑了答案以修复此问题。 - Sman25
你如何从谷歌地图中获取当前位置并返回到你的应用程序,就像在某些应用程序上点击共享位置一样。 - alionthego

10

在按钮点击(操作)时,使用以下代码调用函数“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)
    }
}

编辑您的info.plist以用于LSApplicationQueriesSchemes:

在此输入图片描述

希望会有帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接