I was recently working on an application in which the client had already created all layers with styling according to him. Layers were of different types such as Points, Fill-extrusion, Text, etc. He wanted me to show legends of whatever color scheme he has made in mapbox studio on the front page so his folks can distinguish 43000+ points, which he wanted to display on screen.
So, just as any another task, I start wandering around stackoverflow,medium, etc. But I didn’t found any promising answer. This is what mapbox has to offer to you when you ask for legend. Bummer isn’t it! Turns out that they had something in Mapbox JS but suddenly they decided to not include it inMapbox GL JS.
Don’t worry, I’m here to save you! Actually this is not some kind of coding that you saw in Social Network or any other programming movie.
Turns out that when you do any kind of cosmetic work on layer in Mapbox studio, it looks like they are handling it very sophisticatedly, it is nothing but an array. Take this example: I’m adding color to subcategories but if you click on that button at the bottom ( </> ) which looks like this, you will see array of what I’ve done.
Ironically this is the array you can also find in front end. When you do map.getStyle().layers, you’ll find an array of all layers you have included on your map. When you open the layer that you want for legend, you see Paint property inside which the same array lies. This array contains the condition of coloring (in my case, based on subcategories) and then after that you will have all elements and their respective colors.
You can save that array in a const and then use its individual property to create <div> and <span> of legend and live rest of your life in peace, unless & of course, your client comes up with next crazy problem for you.