How to color individual polygons drawn with mapbox-gl draw?
Asked Answered
K

1

8

I'm reading a GeoJSON file and importing the polygons (and other stuff) into mapbox-gl draw using draw.set(geoJSON). How do I color individual polygons by an attribute in the properties of a feature. Example:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      //"id": "the most unique id in the world",
      "properties": {
        "class_id": 1
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              79.30961608886719,
              61.57192958204744
            ],
            [
              79.34309005737303,
              61.57192958204744
            ],
            [
              79.34309005737303,
              61.57871162332267
            ],
            [
              79.30961608886719,
              61.57871162332267
            ],
            [
              79.30961608886719,
              61.57192958204744
            ]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "class_id": 2
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              79.35201644897461,
              61.58271478278019
            ],
            [
              79.35115814208984,
              61.573972521656835
            ],
            [
              79.38188552856444,
              61.57192958204744
            ],
            [
              79.35201644897461,
              61.58271478278019
            ]
          ]
        ]
      }
    },
    }

The idea is that we color the features with class_id = 1 as red, class_id = 2 as blue, and class_id = 3 as green. How do we do that?

Koester answered 12/7, 2018 at 10:23 Comment(0)
B
15

You need set userProperties to true for the properties of a feature will be available for styling. And use prefix user.

And use case expression:

var Draw = new MapboxDraw({
  userProperties: true,
  styles: [{
      'id': 'gl-draw-polygon-fill-inactive',
      'type': 'fill',
      'filter': ['all', ['==', 'active', 'false'],
        ['==', '$type', 'Polygon'],
        ['!=', 'mode', 'static']
      ],
      'paint': {
        'fill-color': [
          "case", 
          ['==', ['get', "user_class_id"], 1], "#00ff00", 
          ['==', ['get', "user_class_id"], 2], "#0000ff",
          '#ff0000'
        ],
        'fill-outline-color': '#3bb2d0',
        'fill-opacity': 0.5
      }
    }...

[ http://jsfiddle.net/5Lotf4ka/ ]

Beliabelial answered 12/7, 2018 at 12:16 Comment(1)
Thanks! That did it.Koester

© 2022 - 2024 — McMap. All rights reserved.