[GIS] Coloring geojson/topojson tiled using geojson-vt by category

colorgeojsonleaflet

I am mapping polygon data that is tiled on the fly using geojson-vt and leaflet. It works great.

That said, I really need to be able to change the color of each polygon based on its category as stored in a data column (cat1, cat2, cat3, cat4). Right now I am able to define the color of the boarder (strokestyle) and fill (fillStyle), but only for the whole layer.

I have been able to create a fill color that is random using

ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';

How can I bring the category into the mix?

Is this possible, or do I have to utilize a different tiling solution if I want to display by category?

Best Answer

I'd suggest switching to Leaflet.VectorGrid to load data using geojson-vt, and following the Leaflet choropleth tutorial.

In fact, one of the VectorGrid examples deals with the very issue of colouring polygons in different colours depending on a property of each feature:

    var vectorGrid = L.vectorGrid.slicer( euCountries, {
        rendererFactory: L.svg.tile,
        vectorTileLayerStyles: {
            sliced: function(properties, zoom) {

                var p = properties.mapcolor7 % 5;

                return {
                    fillColor: p === 0 ? '#800026' :
                               p === 1 ? '#E31A1C' :
                               p === 2 ? '#FEB24C' :
                               p === 3 ? '#B2FE4C' : '#FFEDA0',
                    fillOpacity: 0.5,
                    stroke: true,
                    fill: true,
                    color: 'black',
                    weight: 0,
                }
            }
        },
        interactive: true
    })

As you can see, the code refers to the mapcolor7 property of each features, performs a modulo operation on it, and chooses a fill colour based on that.

Related Question