It’s straightforward enough to create a new style based on the Traffic Day or Traffic Night style in Studio, but if a developer wants to offer a toggleable traffic overlay, they need to write a nontrivial (but not excessive) amount of code using the runtime styling API.
The proposed example would show how to add traffic lines based on the Mapbox Traffic v1 source to an existing style using the runtime styling API. It would hard-code colors and line widths, but the developer would be free to adjust them as desired – we could even throw in some #colorLiteral
s in the Swift version to make the color scheme easier to tweak.
To ensure that the lines sit beneath any labels and shields in the style, we could hard-code a style layer name, put in a <#placeholder#>
for that layer name, or have the developer dynamically search for the topmost layer that isn’t a symbol style layer:
for layer in style.layers.reversed() {
if !(layer is MGLSymbolStyleLayer) {
style.insertLayer(line, above: layer)
// …
break
}
}
Along these lines, we might want to make it easy for the developer to toggle traffic lines on and off. We could similarly hard-code a list of layer identifiers, or the developer could search for relevant layers dynamically, demonstrating another aspect of the runtime styling API:
var trafficSource = style.sources
.flatMap { $0 as? MGLVectorSource }
.filter { $0.URL == URL(string: "mapbox://mapbox.mapbox-traffic-v1") }
.first
for layer in style.layers {
if let layer = layer as? MGLForegroundStyleLayer,
layer.sourceIdentifier == trafficSource.identifier {
layer.isVisible = showsTraffic
}
}
/cc @friedbunny @bsudekum @mtirwin