Google Map路线开发遇Index out of range致命错误求助
解决Google Maps路线Polyline的"Index out of range"致命错误
嘿,我来帮你排查这个数组越界的问题!这个错误大概率是API请求参数错误,或者解析返回数据时没做安全判断导致的,咱们一步步来解决:
1. 先揪出最可能的根源:URL参数错误
你代码里的URL用了&这个HTML转义字符,但在Swift里直接拼接URL应该用普通的&!这个错误会让Google API无法正确识别destination等后续参数,直接返回空的路线数据,后续解析时访问空数组自然就会越界。
把URL里的&全部替换成&,比如:
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**")
2. 解析数据时必须加安全判断
即使API返回正常,也不能默认路线数组一定有元素,必须先做非空检查。假设你之前的解析代码是直接取routes[0],那改成下面的安全写法:
// 假设你已经拿到了responseJSON的字典数据 guard let routes = responseJSON["routes"] as? [[String: Any]], !routes.isEmpty else { print("没有获取到可用路线数据") return } // 现在再安全访问第一个路线 let firstRoute = routes[0]
3. 完整的修复示例代码
我把你的函数补全并加上所有错误处理,确保每一步都安全:
func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){ let config = URLSessionConfiguration.default let session = URLSession(configuration: config) // 修复URL参数的&问题 let urlString = "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**" guard let url = URL(string: urlString) else { print("URL格式错误,请检查参数拼接") return } let task = session.dataTask(with: url) { data, response, error in if let error = error { print("网络请求出错:\(error.localizedDescription)") return } guard let data = data else { print("没有返回任何数据") return } do { guard let responseJSON = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { print("JSON解析失败") return } // 先检查API返回状态 guard let status = responseJSON["status"] as? String, status == "OK" else { let errorMsg = responseJSON["error_message"] as? String ?? "未知错误" print("API返回错误:\(status) - \(errorMsg)") return } // 安全获取路线数组 guard let routes = responseJSON["routes"] as? [[String: Any]], !routes.isEmpty else { print("没有找到可用路线") return } // 提取Polyline数据 guard let overviewPolyline = routes[0]["overview_polyline"] as? [String: Any], let polylinePoints = overviewPolyline["points"] as? String else { print("无法获取路线Polyline数据") return } // 回到主线程更新地图 DispatchQueue.main.async { let path = GMSPath(fromEncodedPath: polylinePoints) let polyline = GMSPolyline(path: path) polyline.strokeWidth = 3.0 polyline.strokeColor = .systemBlue polyline.map = self.mapView // 替换成你的地图视图实例 } } catch { print("JSON解析出错:\(error.localizedDescription)") } } task.resume() }
4. 额外检查项
- 确认你的API密钥已经启用了Directions API权限,很多人会忘记开这个导致请求被拒绝。
- 检查传入的
source和destination坐标是否有效(纬度范围±90,经度范围±180),无效坐标也会导致API返回空路线。
内容的提问来源于stack exchange,提问作者user9266877
相关产品推荐
相关产品推荐

