we are developing an iOS-App and have a problem with setting the fill color of the MGLFillStyleLayer (MapBox iOS SDK).
We have a large .geojson-file which is parsed and added to the standard MapBox map. Each feature in the geojson has an "color" attribute to set the background-color of the feature. The color is saved as a hex-code.
Is it possible to set the color for each feature individually by using the MapBox expressions or something like "forEach feature -> set fill-color"?
We have tried to change the color by using the expressions MapBox offers for styling ( https://docs.mapbox.com/ios/api/maps/4.1.1/for-style-authors.html ) but couldn't figure out how to load the feature-attribute into a swift-function to generate the color. In the heatmap-example of Mapbox ( https://docs.mapbox.com/ios/maps/examples/heatmap-example/ ) we have seen that it is possible to set fill-color by an NSNumber-Value
let colorDictionary: [NSNumber: UIColor] = [
0.0: .clear,
0.01: .white,
0.15: UIColor(red: 0.19, green: 0.30, blue: 0.80, alpha: 1.0),
0.5: UIColor(red: 0.73, green: 0.23, blue: 0.25, alpha: 1.0),
1: .yellow
]
Maybe we need to define some fixed values like 1 = #db7851, 2 = .... and so on to do it?
For adding the geojson data we are using the following code
let data = try Data(contentsOf: url)
guard let shapeCollectionFeature = try MGLShape(data: data, encoding: String.Encoding.utf8.rawValue) as? MGLShapeCollectionFeature else {
fatalError("Could not cast to specified MGLShapeCollectionFeature")
}
// Create source and add it to the map style.
let source = MGLShapeSource(identifier: "flurstuecke_shape", shape: shapeCollectionFeature, options: nil)
style.addSource(source)
let fillLayer = MGLFillStyleLayer(identifier: "flurstuecke", source: source)
style.addLayer(fillLayer)
For testing purposes we added an touch event for changing the color of the selected feature (just for testing the MapBox expressions).
let spot = sender.location(in: mapView)
let features = mapView.visibleFeatures(at: spot, styleLayerIdentifiers: Set(["flurstuecke"]))
if let feature = features.first, let fbid = feature.attribute(forKey: "FBID") as? String {
guard let layer = mapView.style?.layer(withIdentifier: "flurstuecke") as? MGLFillStyleLayer
else {
fatalError("Could not cast to specified MGLFillStyleLayer")
}
layer.fillColor = NSExpression(format: "TERNARY(FBID = %@, %@, %@)", fbid, UIColor.green, UIColor.blue)
}
We hope, that someone can give us a hint or some documentation that helps us to color each feature. Thanks :)