我在这个主题中进行了搜索,发现了一些我试图在项目中实现的代码,但这无法正常工作!
那么,我想实现什么? 我想在用户界面中有一个按钮,当用户点击按钮时,该应用会在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
答案 0 :(得分:0)
您直接使用<figure class="media-container aspect-ratio-16x9">
<img src="https://picsum.photos/id/1011/500/500" alt="Photo"/>
<figcaption>This is a 16x9 image with a caption</figcaption>
</figure>
错误地创建了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
!