0
votes

I am trying to implement clustering in Mapbox in IOS. I want to change color for unclustered StyleLayer depending on specific attribute in MGLPointFeature. following is the code for single feature :

let feature = MGLPointFeature()
feature.coordinate = CLLocationCoordinate2D(latitude: site.latitude, longitude: site.longitude)
feature.attributes = ["id": site.siteId, "siteCode": site.siteCode, "risk": site.riskId]

in above snippet, I want to use this attribute ("risk": site.riskId) to generate different colors for icon which is set by using following code:


style.setImage(icon.withRenderingMode(.alwaysTemplate), forName: "icon")

let ports = MGLSymbolStyleLayer(identifier: "ports", source: source)
ports.iconImageName = NSExpression(forConstantValue: "icon")    
ports.predicate = NSPredicate(format: "cluster != YES")
ports.iconAllowsOverlap = NSExpression(forConstantValue: true)
style.addLayer(ports)

and following are the colors for each riskId :

let risks = [
        0: Color.cellBackgroundColor,
        1: UIColor.from(hexString:  "B9E5D1"),
        2: UIColor.from(hexString:  "95E9FF"),
        3: UIColor.from(hexString:  "FCE2A6"),
        4: UIColor.from(hexString:  "FCE2A6")
    ]

I have an idea that I can get these results using NSExpression for feature attributes. But have no idea how to implement it. Can anyone please help me get this done. Thanks

1

1 Answers

0
votes

So, I was able to solve this problem. For this I added an attribute "siteRiskColor" in Feature and gave it the value depending on value of risk as

let riskId = site.riskId
            var color = "B0E5A1"
            if  riskId == 1 {
                color = "B0E5A1"
            } else if riskId == 2 {
                color = "99E9FF"
            } else if riskId == 3 {
                color = "FCD2A6"
            } else if riskId == 4 {
                color = "FBC3A9"
            }

and then added different images for each color mentioned above and name them same as above. Then, while making icon for un-clustered style image I added following lines to pick different images.

let site = MGLSymbolStyleLayer(identifier: "site", source: source)
 site.iconImageName = NSExpression(forKeyPath: "siteRiskIcon")

and it worked!