我想使用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 :)'方法。 –