Search code examples
mapboxmapbox-ios

Mapbox iOS: MGL_IF Expression


I want to color my MGLSymbolStyleLayer feature icons based on multiple if conditions, which requires the use of MGL_IF, but I'm getting this runtime error: 'Unable to parse the format string...'

projectsLayer!.iconColor =
          NSExpression(format: "MGL_IF(location_name IN %@, %@, location_name = United States,  %@)",
                       uniqueLocations, savedColor, defaultColor)

Note, for something simple like this I can use a ternary operator and that's working fine for me. But I need to add multiple conditions for multiple colors and so I need to use MGL_IF or something similar.


Solution

  • It appears that a regression in the Maps SDK caused by a change in Apple’s iOS/macOS SDK is causing this behavior with MGL_IF. As a workaround, you can either use the TERNARY() or MGL_MATCH() operators as outlined below:

    TERNARY() only supports a single case. (MGL_IF​ is no different than TERNARY and is not necessary.) For multiple cases, you need to either nest TERNARY(foo = bar, 'A', TERNARY(bar = baz, 'B', 'C')):

    coloredLayer.fillColor = NSExpression(format: "TERNARY(location_name = 'United States', %@, TERNARY(location_name = 'Russia', %@,))", UIColor.white, UIColor.green, UIColor.magenta)
    

    Or use MGL_MATCH():

    coloredLayer.fillColor = NSExpression(format: "MGL_MATCH(location_name, 'United States', %@, 'Russia', %@, 'Brazil', %@, 'Venezuela', %@, %@)", UIColor.white, UIColor.lightGray, UIColor.purple, UIColor.systemTeal, UIColor.yellow)
    

    which will result in the United States being colored while, Russia colored light gray, Brazil colored purple, Venezuela colored teal and everything else colored yellow.