I am trying to draw route between two points but not able to do so beacuese there is nill value in my polypoints. This is how I am doing it :
Parsing 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)
}
}
}
}
Till polystring I am getting values but not getting any value for this line of code if let polyString = overview_polyline["points"] as? String
.
Any idea why polyString
is nil ?
I have gone through this link to clear the concepts still not able to implement it. unexpectedly found nil while unwrapping an Optional value
I achieved this by modifying above code to this code. So to parse google api and create a polyline on map, you can use this code, written in 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
}
})
}