0
votes

I want to return the fill-color of a layer so it can be used as a variable to populate a dynamic legend on a printable map which is being built as a separate document.

The browser will only pick up hex colors but getPaintProperty returns hsl. I know that Mapbox holds this information against the style/layers i just can't figure out how to access it.

Is there a way to return hex values of layer fill-colors instead?

This is the generic code i am using to access each layers fill-color;

    map.on("render", function() {
    if(map.loaded()) {
    console.log(map.getPaintProperty('layer id','fill-color'));
    }
    });

My current alternative is to use an additional library to perform the conversion.

1

1 Answers

0
votes

You can just use a generic rgba to hex function:

 //Function to convert hex format to a rgb color
function rgb2hex(rgb){
     rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
     return (rgb && rgb.length === 4) ? "#" +
         ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
         ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
         ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
 }

rgb2hex(map.getPaintProperty('park', 'fill-color'));

returns "#e6ebcc"