Search code examples
javascriptmapboxmapbox-gl-jsmapbox-gl

How to set individual layout properties for feature points with mapbox-gl?


I have an array of feature points, and wan't to update some layout properties on each feature point, individually. How to I do this?

This is what I have so far.

const features = getVisibleFeatures();
// This updates all. Not what I wan't. Each feature should have different offset.
map.setLayoutProperty("ports", "text-offset", [5, 5]);

Each feature should have it's own text-offset, based on individual values. How do I achieve this?

Update

@steve-bennett offers some great suggestion in the comments below, but unfortunately they don't work with layout properties and the text-offset values.

It's important that a solution can work with this.


Solution

  • After a lot of searching, trial and error, I figured out I could do this:

    map.setLayoutProperty("ports", "text-offset", {
        property: "id",
        type: "categorical",
        stops: [
          ["0", [2, 1]],
          ["1", [2, 0]],
          ["2", [0, 2]],
        ],
        default: [0, 0],
    });
    

    "0", "1" and "2" is matched against the properties.id field. So I can do something like this:

      map.setLayoutProperty("layout-id", "text-offset", {
        property: "id",
        type: "categorical",
        stops: nodes.map((node) => {
          const x = node.vx;
          const y = node.vy;
          return [node.id, [x, y]];
        }),
        default: [0, 0],
      });