如何使用 MapBox 在街道名称下画一条线

How to draw a line under street name using MapBox

我想用 Mapbox 绘制路线。我试过添加折线:

let polyline = MGLPolyline(coordinates: &coords, count: UInt(coords.count))
mapView?.add(polyline)

但它一直在街道名称之上绘制。我怎样才能移动到街道名称下方?

如果将 MGLPolyline 直接添加到 MGLMapView,则将其添加为注释;目前 Mapbox iOS SDK 仅支持在所有内容之上添加注释。

但是,SDK 有一个单独的 API 称为 runtime styling, which allows you to place data under or above any layer of the map. From this example,您可以使用如下代码将 shape source 添加到地图样式和渲染形状源的 线层 。 (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 还提供了完整的分路段导航 UI,包括为显示路线而优化的地图。