Search code examples
angularmapboxgeojsonmapbox-gl-jsdata-driven

Mapbox Get Expression with Interpolated Text Sizes


I would like to add just a single layer for text symbols that are being added from a FeatureCollection. There are multiple text sizes and styles associated to each feature, held within their properties. I have been using the data driven expressions available with Mapbox to assign the styles.

Within the properties of each feature there is an array named 'text_size', which holds an interpolated text size intended to be retrieved with the ['get', 'text_size'] expression. An example of what is held in the 'text_size' property of a feature is shown below.

text_size: [
  'interpolate',
  ['linear'],
  ['zoom'],
  18,
  0,
  20,
  8,
  22,
  20
]

The problem is the ['get', 'text_size'] expression does not seem to work to set the value. Example code using the expression which is not working shown below. There are no errors being thrown, the text size is just getting set to the default size.

this.map.addLayer({
        id: `text-dynamic-layer`,
        type: 'symbol',
        source: `dynamic-text-source`,
        layout: {
          'text-size': ['get', 'text_size'],
          'text-font': ['Open Sans Regular'],
          'text-offset': [0.85, -1.7],
          'text-anchor': 'top',
          'text-max-width': 8,
          'text-field': '{name}'
        },
        paint: <any>{
          'text-color': '#FFF',
        },
      });

The same values do work when the array is applied directly, rather than being retrieved with the ['get', 'text_size'] expression. An example of the code used which is working correctly when adding a layer without the expression is shown below.

this.map.addLayer({
        id: `text-dynamic-layer`,
        type: 'symbol',
        source: `dynamic-text-source`,
        layout: {
          'text-size': [
            'interpolate',
            ['linear'],
            ['zoom'],
            18,
            0,
            20,
            8,
            22,
            20
          ],
          'text-font': ['Open Sans Regular'],
          'text-offset': [0.85, -1.7],
          'text-anchor': 'top',
          'text-max-width': 8,
          'text-field': '{name}'
        },
        paint: <any>{
          'text-color': '#FFF',
        },
      });

Any ideas what could be causing this? Thanks in advance for any responses.


Solution

  • You can't store an expression on a feature and have it interpreted in that way. Well, not afaik.

    If it's really important that each feature can set its own font size for those three different zoom levels, I'd suggest storing them directly and having an expression like:

    "font-size": ['interpolate', ['linear'], ['zoom'], 18, ['get', 'font18'], 20, ['get', 'font20'], 22, ['get', 'font22']]