我想使用Mapbox绘制路线。我尝试添加多段线:如何使用MapBox在街道名称下绘制线条
let polyline = MGLPolyline(coordinates: &coords, count: UInt(coords.count))
mapView?.add(polyline)
但它一直绘制在街道名称的顶部。我如何在街道名下移动?
我想使用Mapbox绘制路线。我尝试添加多段线:如何使用MapBox在街道名称下绘制线条
let polyline = MGLPolyline(coordinates: &coords, count: UInt(coords.count))
mapView?.add(polyline)
但它一直绘制在街道名称的顶部。我如何在街道名下移动?
如果您将MGLPolyline
直接添加到MGLMapView
,您将其添加为注释;目前,Mapbox iOS SDK仅支持在所有内容上添加注释。
但是,SDK有一个独立的API,名为runtime styling,它允许您将数据放置在地图的任何图层下方或上方。从this example,您可以使用类似以下的代码将形状源添加到地图的样式和线条层,呈现形状源。 (MGLLineStyleLayer
让人想起MapKit的MKOverlayPathRenderer
的。)
let routeFeature = MGLPolylineFeature(coordinates: &coords, count: UInt(coords.count))
let routeSource = MGLShapeSource(identifier: "route", shape: routeFeature, options: nil)
mapView.style?.addSource(routeSource)
let routeLayer = MGLLineStyleLayer(identifier: "route", source: routeSource)
// Set properties like lineColor, lineWidth, lineCap, and lineJoin
mapView.style?.insertLayer(routeLayer, above: roadLayer) // or below: labelLayer
上面的代码工作,如果你知道在路上或标签层的识别符。您可以通过打开Mapbox Studio中的样式来获取标识符。为了更强大的功能,您可以迭代地图样式中的所有图层,将路径图层插入到您找到的第一个非符号图层上方。 (标签和图标使用符号图层渲染。)
for layer in style.layers.reversed() {
if !(layer is MGLSymbolStyleLayer) {
style.insertLayer(routeLayer, above: layer)
break
}
}
顺便说一句,如果你需要的不仅仅是路径线以上,Mapbox Navigation SDK for iOS配备了一个完整的turn-by-turn导航UI,包括经过优化的地图用于显示路线。
如果我知道标识符,应该如何创建'roadLayer'?我尝试了这样的尝试 'let roadLayer = MGLStyleLayer(identifier:“roadLayerIdentifier”)',当我尝试添加'routeLayer'时,失败:'mapView?.style?.insertLayer(routeLayer,above:roadLayer)' – Xernox
@Xernox,'MGLStyleLayer(identifier:)'创建一个新的样式图层。要获取对现有的表示道路的样式图层的引用,请在'MGLStyle'上调用'layer(withIdentifier :)'方法。 –