我想知道两个坐标之间的所有可能路线 ,谷歌地图api只给我一条路线,使用这个网址:" https://maps.googleapis.com/maps/api/directions/json?origin=30.1124,31.4003&destination=29.9792,31.1342&provideRouteAlternatives=true&key=xx")
我无法找到所有路线的位置并获取它们
这是代码
func getRoutes(handler:@escaping (_ error: String?) -> Void){
let request = URLRequest(url: URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=30.1124,31.4003&destination=29.9792,31.1342&provideRouteAlternatives=true&key=AIzaSyAf5emsTReEhPgC3NwAnXEdoa_CllLbyLc")!)
// request.addValue("provideRouteAlternatives", forHTTPHeaderField: "true")
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
if error != nil {
// Handle error...
handler("Connection Error")
return
}
let parsedResult: [String: AnyObject]!
do {
parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: AnyObject]
print(parsedResult)
} catch {
print("Error parsing result as JSON")
handler("Cant download Student data")
return
}
if let array = parsedResult["routes"] as? NSArray {
if let routes = array[0] as? NSDictionary{
if let overview_polyline = routes["overview_polyline"] as? NSDictionary{
if let points = overview_polyline["points"] as? String{
print(points)
// Use DispatchQueue.main for main thread for handling UI
DispatchQueue.main.async {
// show polyline
let path = GMSPath(fromEncodedPath:points)
let polyline = GMSPolyline(path: path)
//self.polyline.path = path
polyline.strokeWidth = 4
polyline.map = self.myMap
}
}
}
}
}
handler(nil)
}
task.resume()
}
答案 0 :(得分:1)
所有路由都出现在JSON响应中的 routes 数组中。
如果您指定了特定的 origin 和 destination ,我会在API响应中的 routes 数组中只看到一个元素。但 https://www.google.co.in/maps/dir/'30.1124,31.4003'/'29.9792,31.1342'/ 会在网络版上显示多条路线。
除非Google在JSON响应中提供所有路线,否则您的程序中可能无法执行任何操作。