I know this is a pretty basic question, but I'm fairly new with JavaScript and Mapbox. I have a map that I created in Mapbox Studio. Now I'm using GL JS to create an interactive map for my website. I want to be able to toggle layers, so I'm using this tutorial: https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/

My issue is that in the example, they first add layers to a blank map. I have the layers already on my map from adding to my style in Studio. So, I can take out the map.addSource and map.addLayers parts of the code because I don't need to add layers. But then when creating the toggle button, it doesn't point to the layers from my Studio style. What do I need to add to reference the two layers already in my style?

  • 1
    I can't think of any problems, if the names match the published styles layers. Could you share some minimal code? Commented Sep 19, 2019 at 14:20
  • Here's my code: codepen.io/melissad34/pen/GRKYBMQ Thanks!
    – Melissa
    Commented Sep 20, 2019 at 15:04
  • That seems to be working fine to me...? Commented Sep 20, 2019 at 23:15

1 Answer 1


This appears to be working based on the codepen you posted, as AndrewHarvey noted.

Basically you just need to look in your style to find the layerID. In your case the two layers are 'units' and 'percchange'. In the Mapbox example you posted they are 'museums' and 'contours'. The layers, regardless if they are added through GL JS or studio, can be referenced using these IDs.

Hope that helps your understanding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.