Search code examples
javascriptperformancemapboxmapbox-gl-jsmapbox-gl

mapbox-gl-js filter or data-driven properties


This a question is for someone that knows how mapbox-gl-js works internally.

Use case: we want to display 2 polygons with 2 different colors depending on the property region.

Currently, using mapbox-gl-js, you have 2 way of defining a style depending on data:

  1. Using filter:
{
  "id": "region_sud",
  "filter": [
    "all",
    [
      "==",
      "sud",
      ["get", "region"]
    ]
  ],
  "paint": {
    "fill-color": "#F27E00",
  },
  "source": "region",
  "source-layer": "region",
  "type": "fill"
},{
  "id": "region_nord",
  "filter": [
    "all",
    [
      "==",
      "nord",
      ["get", "region"]
    ]
  ],
  "paint": {
    "fill-color": "#007E00",
  },
  "source": "region",
  "source-layer": "region",
  "type": "fill"
}
  1. Use data-driven style property
{
  "id": "region",
  "paint": {
    "fill-color": [
      "case",
      ["==", ["get", "region"],"sud"],
      "#F27E00",
      ["==", ["get", "region"],"nord"],
      "#007E00",
      "#000000",
    ],
  },
  "source": "region",
  "source-layer": "region",
  "type": "fill"
}

I would say the best option is the method 2 because we only have to create one style instead of 2.

But what if there is 20 or 200 differents regions to draw. Which solution will be the best in terms of performance?


Solution

  • If you define 20- 200 layers , map rendering becomes slow... So of course considering them as a single layer and using data driven styles is a better approach.

    you can take a look at the documentation