3

Is is possible to set the fill-color stops, based on a text property rather than a numeric value

e.g fill based on province name

My input dataset has a property/Column called PROV_ID and contains a 2 letter ID for each state/Province

So I am aiming toward something in the lines of: 'stops': [['GP', 'YELLOW']]

The code however does not render any fill-colors when when implemented as shown below, I have replaced my PROV_ID in the code below with the Primary key property [numeric] to test, and that works fine

I guess the question is really then if fill-color stops is limited to numeric properties only?

map.addLayer({
        'id': 'countiesLayer',
        'type': 'fill',    /*define the type of layer fill, line, point, fill-extrusion, background, raster, circle*/
        'source': 'mySrcName',
        'source-layer': '3_Fields-83vr21',
        'layout': {
          'visibility': 'visible'
        },

        /*there are many options for styling - this is a simple style*/
        'paint': {
          'fill-color': {
            'property': 'PROV_ID',
            'stops': [['GP', 'YELLOW']]
          },
          'fill-outline-color': 'white'
        }
      });
Cor Basson
  • 43
  • 1
  • 5

1 Answers1

7

I think you need an expression with the function match.

The code would be (not tested):

map.addLayer({
    'id': 'countiesLayer',
    'type': 'fill',    /*define the type of layer fill, line, point, fill-extrusion, background, raster, circle*/
    'source': 'mySrcName',
    'source-layer': '3_Fields-83vr21',
    'layout': {
      'visibility': 'visible'
    },

    /*there are many options for styling - this is a simple style*/
    'paint': {
      'fill-color': ['match', ['get', 'PROV_ID'], // get the property
                     'GP', 'yellow',              // if 'GP' then yellow
                     'XX', 'black',               // if 'XX' then black 
                     'white']                     // white otherwise
      },
      'fill-outline-color': 'white'
    }
  });

From the docs:

match

Selects the output whose label value matches the input value, or the fallback value if no match is found. The input can be any string or number expression (e.g. ["get", "building_type"]). Each label can either be a single literal value or an array of values.

["match",
input: InputType (number or string),
label_1: InputType | [InputType, InputType, ...], output_1: OutputType,
label_n: InputType | [InputType, InputType, ...], output_n: OutputType, ...,
default: OutputType ]: OutputType
Ronie
  • 530
  • 5
  • 9