swift - 无法从 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
解决方案
您错误地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 }
推荐阅读
- javascript - 尝试在 Node JS 中访问导出的函数
- file - 将文件上传到 .net core 3.1 API - 只收到一半文件
- python - 如果刻度是标签而不是数字,如何扩展 matplotlib 轴?
- sorting - 是否有等效于 boost::multi_index 容器,它同时按多个索引排序?
- flutter - 编辑颤振 BasicTimeField
- python - 如何在 ModelAdmin 中覆盖 Django get_search_results 方法,同时保持过滤器按预期工作?
- ant - ANT 的 Gitlab CI 管道
- java - 未找到 Internet Explorer 缓存导致的异常。java.net.UnknownHostException
- performance - 移动超过 3000 点时的折线性能问题变得太慢
- python - 用 BS4 抓取网站 // 访问类