首页 > 解决方案 > 无法从 GoogleMaps 获取路线,因为“​​found nil”解开 URL

问题描述

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

那么,我想实现什么?我想在 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

标签: swiftxcodegoogle-mapsmapsdirections

解决方案


您错误地urlString直接使用创建,CLLocationCoordinate2D因为您必须使用它的属性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 }

推荐阅读