iOS中Swift开发Google Maps路线绘制:旧坐标失效问题求助
解决思路:旧坐标无法生成导航路线的问题
看起来你遇到的问题大概率和请求缓存或者API返回的异常数据未处理有关,我给你梳理几个可行的排查方向:
1. 优先排查URLSession的缓存问题
URLSession默认会对GET请求的响应进行本地缓存,如果之前用旧坐标请求时,API返回了错误(比如无路线、权限问题),缓存会一直保留,即使重启APP也会直接复用缓存的错误结果,而不会重新发起请求。而新坐标是首次请求,没有缓存,所以能正常获取数据。
解决方法是给请求设置忽略本地缓存的策略,修改你的代码:
func route(){ let origin = "35.6800,51.3819" let destination = "35.6820,51.3769" let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=\(googleApiKey)" guard let url = URL(string: urlString) else { print("无效的URL") return } // 创建请求并禁用缓存 var request = URLRequest(url: url) request.cachePolicy = .reloadIgnoringLocalCacheData URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in if let error = error { print("请求错误: \(error.localizedDescription)") return } guard let data = data else { print("未获取到数据") return } do{ let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String : Any] guard let routes = json["routes"] as? NSArray, routes.count > 0 else { print("API未返回有效路线") return } OperationQueue.main.addOperation({ let route = routes[0] as! NSDictionary let routeOverviewPolyline = route.value(forKey: "overview_polyline") as! NSDictionary let points = routeOverviewPolyline.object(forKey: "points") as! String let path = GMSPath(fromEncodedPath: points) let polyline = GMSPolyline(path: path) polyline.strokeWidth = 3 self.mapView.clear() if let path = path { let bounds = GMSCoordinateBounds(path: path) self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0)) } polyline.map = self.mapView }) }catch let error as NSError{ print("JSON解析错误:\(error)") } }).resume() }
2. 直接验证旧坐标的API响应
把旧坐标对应的URL复制到浏览器中打开,查看返回的JSON内容:
- 如果
routes数组为空,说明这两个地点之间确实没有符合条件的驾驶路线,或者你的API密钥没有正确启用Directions API权限; - 如果返回错误信息(比如
status字段为ZERO_RESULTS或REQUEST_DENIED),根据错误提示调整坐标或API配置。
3. 完善代码的错误处理逻辑
你的原代码没有处理routes为空的情况,如果API返回无路线,routes[0]会直接导致崩溃,但你可能没捕获到这个错误。上面修改后的代码已经加了routes.count > 0的判断,能帮你定位问题。
4. 确保URL参数编码正确
虽然你的坐标是纯数字,但如果后续坐标包含特殊字符(比如空格、中文),会导致URL无效。可以提前对参数进行URL编码:
let originEncoded = origin.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let destinationEncoded = destination.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(originEncoded)&destination=\(destinationEncoded)&mode=driving&key=\(googleApiKey)"
内容的提问来源于stack exchange,提问作者maral
相关产品推荐
相关产品推荐

