我试图在两点之间绘制路线但是不能这样做beacuese在我的polypoints中有nill值。 我就是这样做的:
解析JSON:
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
if let routes = json["routes"] as? [Any]{
if let overview_polyline = routes[0] as?[String:Any]{
print("overview_polyline\(overview_polyline)")// Getting values till here
if let polyString = overview_polyline["points"] as? String{
//Call this method to draw path on map
self.showPath(polyStr: polyString)
}
}
}
}
直到polytring我得到了值但没有得到这行代码if let polyString = overview_polyline["points"] as? String
的任何值。
知道为什么polyString
nil ?
我已经通过此链接来清除仍然无法实现它的概念。 unexpectedly found nil while unwrapping an Optional value
答案 0 :(得分:4)
我通过将上面的代码修改为此代码来实现此目的。因此,要解析谷歌api并在地图上创建折线,您可以使用此代码,用swift 3编写。
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
let routes = json["routes"] as! NSArray;
print(routes)
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
polyline.map = self.mapView
}
})
}