我想在我的谷歌地图应用程序上有一条路线,我使用此代码 - >
func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=walking&key=**MY KEY**")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
}else{
do {
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
let routes = json["routes"] as? [Any]
let overViewPolyLine = routes?[0] as?[String:Any]
let polyString = overViewPolyLine?["points"] as?String
//Call this method to draw path on map
self.showPath(polyStr: polyString!)
}
}catch{
print("error in JSONSerialization")
}
}
})
task.resume()
}
func showPath(polyStr :String){
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.map = googleMapsView // Your map view
}
我迷恋这一行 - >
我该怎么做才能解决这个问题?
答案 0 :(得分:0)
如果在索引0处出现超出范围的异常,则该数组为空。
使用可选绑定来安全地打开选项。
if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
let routes = json["routes"] as? [[String:Any]], // don't use [Any] if the type is more specific
let overViewPolyLine = routes.first,
let polyString = overViewPolyLine["points"] as? String {
//Call this method to draw path on map
self.showPath(polyStr: polyString)
}