【问题标题】:Can't get directions from GoogleMaps because of "found nil" unrapping URL由于“found nil”展开 URL,无法从 Google 地图获取路线
【发布时间】:2019-06-14 14:57:00
【问题描述】:

我搜索了这个主题,发现了一些我试图在我的项目中实现的代码,但它不起作用!

那么,我想实现什么? 我想在 UI 中有一个按钮,当用户点击按钮时,应用程序会显示到 GoogleMap 上特定点的方向。但是我的函数在 URL 上崩溃了。

这是我的代码:

func draw(src: CLLocationCoordinate2D, dst: CLLocationCoordinate2D){

    let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src)&destination=\(dst)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key

    let url = URL(string: urlString)  // Here is the crash!

    URLSession.shared.dataTask(with: url!, completionHandler: {
        (data, response, error) in
        if(error != nil){
            print("error")
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
                let routes = json["routes"] as! NSArray
                self.mapView.clear()

                OperationQueue.main.addOperation({
                    for route in routes
                    {
                        let routeOverviewPolyline:NSDictionary = (route as! NSDictionary).value(forKey: "overview_polyline") as! NSDictionary
                        let points = routeOverviewPolyline.object(forKey: "points")
                        let path = GMSPath.init(fromEncodedPath: points! as! String)
                        let polyline = GMSPolyline.init(path: path)
                        polyline.strokeWidth = 3

                        let bounds = GMSCoordinateBounds(path: path!)
                        self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0))

                        polyline.map = self.mapView

                    }
                })
            }catch let error as NSError{
                print("error:\(error)")
            }
        }
    }).resume()
}

我不知道问题可能出在 API 密钥上,还是其他问题。我读到空格等可能会导致此问题,但我找不到问题所在!

错误信息:

Fatal error: Unexpectedly found nil while unwrapping an Optional value
2019-06-14 16:50:45 Fatal error: Unexpectedly found nil while unwrapping an Optional value

【问题讨论】:

    标签: swift xcode google-maps maps directions


    【解决方案1】:

    您错误地使用CLLocationCoordinate2D 直接创建urlString,因为您必须使用它的属性latitude/longitude

    let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src)&destination=\(dst)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key
    

    应该是

    let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src.latitude),\(src.longitude)&destination=\(dst.latitude),\(dst.longitude)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key
    

    另外最好避免! 并做

    guard let url = URL(string: urlString) else { return }
    

    【讨论】:

    • *** 由于未捕获的异常“GMSThreadException”而终止应用程序,原因:“必须从主线程调用 API 方法”
    • self.mapView.clear() 也应该在主操作中
    • 我把它放在 OperationQueue.main.addOperation({ 中,没有错误/异常!但它不会在地图上绘制折线。
    • 确保设置 mapView 委托并实现所有需要的方法
    • 路线是空的,我不明白为什么!这就是问题所在,"json["routes"] as! NSArray 导致错误/空。我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2012-01-03
    • 2019-08-11
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多