Mapbox Navigation V3无法展示多目的地NavigationRoute的解决方案咨询
要同时展示前往不同目的地的路线,你不需要修改Mapbox原生方法,只需绕过show/showcase的默认逻辑,手动创建并添加自定义路线注解即可。官方的NavigationRoutes设计初衷是承载同一目的地的主路线与备选路线,而多目的地路线属于独立路线组,因此需要手动管理地图注解来实现。
具体实现步骤
- 定义数组保存所有不同目的地的
Route实例 - 计算得到每条路线后,将其加入数组并触发手动展示逻辑
- 遍历所有路线,创建自定义路线注解并添加到地图中
修改后的代码示例
首先添加用于存储所有路线的数组:
// 保存所有不同目的地的路线 var allRoutes: [Route] = []
修改路线计算后的处理逻辑:
let userWaypoint = Waypoint( location: CLLocation(latitude: location.latitude, longitude: location.longitude), name: "user" ) let destinationWaypoint = Waypoint(coordinate: CLLocationCoordinate2D(latitude: destination.latitude, longitude: destination.longitude)) let navigationRouteOptions = NavigationRouteOptions(waypoints: [userWaypoint, destinationWaypoint]) let task = mapboxNavigation.routingProvider().calculateRoutes(options: navigationRouteOptions) Task { [weak self] in switch await task.result { case .failure(let error): print(error.localizedDescription) case .success(let response): guard let self else { return } // 将当前目的地的主路线加入数组 allRoutes.append(response.mainRoute) // 手动展示所有路线 self.showMultipleRoutes() } }
实现手动展示多路线的方法(推荐使用RouteLine贴合Mapbox原生样式):
func showMultipleRoutes() { // 先清除之前的路线注解 navigationMapView.mapView.annotations?.forEach { annotation in if annotation is RouteLine || annotation is RouteLineArrow { navigationMapView.mapView.removeAnnotation(annotation) } } // 为不同路线分配区分颜色 let routeColors: [UIColor] = [.systemBlue, .systemRed, .systemGreen, .systemOrange] // 遍历所有路线,创建并添加RouteLine for (index, route) in allRoutes.enumerated() { let routeLine = RouteLine(route: route) routeLine.style = RouteLineStyle( routeColor: routeColors[index % routeColors.count], routeWidth: 5 ) navigationMapView.mapView.addAnnotation(routeLine) } // 自动调整地图视野,显示所有路线 guard let allCoordinates = allRoutes.flatMap({ $0.coordinates }) else { return } let bounds = MKCoordinateRegion( coordinates: allCoordinates, padding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100) ) navigationMapView.mapView.setRegion(bounds, animated: true) }
补充说明
- 如果你需要更基础的路线绘制,也可以用
MGLPolyline+MGLLineStyleLayer的组合实现,逻辑类似,只是样式需要手动配置更多细节。 - 该方案完全基于Mapbox公开的API实现,无需修改原生代码,同时保留了路线交互的灵活性。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

