Mapbox gl js interpolate marker text-offset pitch

490 Views Asked by At

How can I interpolate the text-offset of a marker depending on pitch?

Interpolation is perfectly working for:

'text-size': ['interpolate', ['linear'], ['zoom'], 10, 10, 18, 20],

but for text-offset it is not working.

'text-offset': ['interpolate', ['linear'], ['pitch'], 10, [0.2, 0], 18, [2, 0]],

What am I doing wrong?

'layout': {
          'text-field': ['get', 'name'],
          'text-font': [
                        'Open Sans Semibold',
                        'Arial Unicode MS Bold'
                       ],
          'text-size': ['interpolate', ['linear'], ['zoom'], 10, 10, 18, 20],
          'text-rotate': -90,
        //'text-offset': [2, 0],
          'text-offset': ['interpolate', ['linear'], ['pitch'], 10, [0.2, 0], 18, [2, 0]],
          'text-anchor': 'left',
          'text-allow-overlap': true
          },
   paint: {
          "text-color": "rgba(0, 100, 50, 0.9)",
          }
1

There are 1 best solutions below

0
Taku On

The only allowed camera expression is zoom, and so you need to set this text-offset value after each movement like below:


const map = new mapboxgl.Map({});

map.on('pitch', () => {

  console.log('A pitch event occurred.');

  map.setLayoutProperty(layerId, 'text-offset', newValue)

  // More about setLayoutProperty https://docs.mapbox.com/mapbox-gl-js/api/map/#map#setlayoutproperty
});

If you see performance issues, you may want to change map.on('pitch') to map.on('moveend') and compare map.getPitch() to previous pitch value to evaluate if you should change the text-offset value. More about each API below:

Map.getPitch

Map.event:moveend

Map.event:pitch