0

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.

benj
  • 113
  • 3
  • 11

1 Answers1

0

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"

CCantey
  • 306
  • 1
  • 14
  • I was hoping for a way to draw down the hex instead of the hsl direct from MapBox (it definitely stores it against the style) but it doesn't currently seem to be exposed through the API. In lieu of that this is a suitable alternative for me. Cheers. – benj Apr 13 '16 at 09:52