Mapbox路线绘制后无法从MapView清除问题求助(附代码)
解决MapView无法清除折线路线的问题
嘿,这个清除路线的问题我熟!你现在的问题是每次调用drawRoute()的时候都在给地图新增路线相关的数据源和图层,但旧的那些还留在MapView的样式里,所以看起来像是没法清除对吧?给你两个实用的解决办法:
方法一:彻底移除旧的数据源和图层
先写一个专门的清除函数,每次绘制新路线前调用它,把之前的路线相关资源全部清理掉:
func clearRoute() { // 移除路线图层 if let lineLayer = style.layer(withIdentifier: "polyline") as? MGLLineStyleLayer { style.removeLayer(lineLayer) } // 移除对应的数据源 if let source = style.source(withIdentifier: "polyline") as? MGLShapeSource { style.removeSource(source) } }
然后修改你的drawRoute()函数,在绘制新路线前先执行清除操作:
func drawRoute() { // 先清除旧路线 clearRoute() var routeCoordinates = route.coordinates! let polyline = MGLPolylineFeature(coordinates: &routeCoordinates, count: route.coordinateCount) let source = MGLShapeSource(identifier: "polyline", features: [polyline], options: nil) style.addSource(source) let layer = MGLLineStyleLayer(identifier: "polyline", source: source) layer.lineJoin = MGLStyleValue(rawValue: NSValue(mglLineJoin: .round)) // 这里可以补充你需要的其他样式设置 layer.lineColor = MGLStyleValue(rawValue: UIColor.blue) layer.lineWidth = MGLStyleValue(rawValue: 3.0) style.addLayer(layer) }
方法二:清空数据源的内容(适合频繁切换路线的场景)
如果不想每次都移除和重新添加数据源/图层,也可以直接清空数据源里的路线特征:
func clearRoute() { if let source = style.source(withIdentifier: "polyline") as? MGLShapeSource { // 清空数据源中的所有特征,旧路线就会消失 source.features = [] } }
这个方法的好处是不用频繁操作图层和数据源的添加/移除,性能更优,适合需要频繁更新路线的场景。
关键提示
一定要注意使用统一的标识符(这里是"polyline"),这样才能准确找到要清除的资源,别在不同地方用不同的标识符哦!
内容的提问来源于stack exchange,提问作者sametbilgi
相关产品推荐
相关产品推荐

