Swift - 使用URL打开Goog​​le地图

时间:2015-12-23 22:03:00

标签: ios swift google-maps

我正在尝试使用特定网址(显示某人的位置)在我的应用内启动Google地图。尽管如此,作为第一步,我正在尝试使用Google Maps iOS API示例代码,但我收到了错误消息。

这是我的功能:

@IBAction func goToHomeAddressPressed(sender: AnyObject) {

        /*Get Coordinates From User Object*/
        if(self.userObject.homeAddress[0] != "" && self.userObject.homeAddress[1] != "")
        {
            let lat: String = self.userObject.homeAddress[0]
            let lon: String = self.userObject.homeAddress[1]

            print("Address: \(self.userObject.homeAddress[0]) and \(self.userObject.homeAddress[1])")

                if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
                UIApplication.sharedApplication().openURL(NSURL(string:
                    "comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic")!)
            } else {
                print("Can't use comgooglemaps://");
            }
        }else{
            print("Problem opening Google Maps with specified address")
        }


    }

地址坐标不为空,它们打印到控制台。但我收到此错误消息:

-canOpenURL: failed for URL: "comgooglemaps://" - error: "(null)"
Can't use comgooglemaps://

我在另一个Stackoverflow线程中读到,我必须将值插入到info.plist中。我默认有这些:

enter image description here

如果有人能告诉我发生了什么,我真的很感激。

谢谢,

3 个答案:

答案 0 :(得分:3)

如果你只需要在谷歌地图中打开一个位置,你应该尝试使用这样的东西 https://maps.google.com/?q=@37.3161,-122.1836

这将打开谷歌地图与网址中提供的坐标,如果谷歌地图没有安装在设备上,它将打开safari将相同的网址。 谷歌网址计划https://developers.google.com/maps/documentation/ios-sdk/urlscheme

答案 1 :(得分:0)

正如评论中所述,您可能没有安装Google地图应用。请在设备(iPhone / iPod / iPad)上测试您的代码,并且该设备应安装Google地图应用。由于您的设备未安装Google地图应用,因此无法使用

答案 2 :(得分:0)

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