To omit Legend, you have to set Legend::LayerInfos parameter which LayerInfo you want to show. As bellow,
//add the legend
dojo.connect(map,'onLayersAddResult',function(results){
var layerInfo = dojo.map(results, function(layer,index){
return {layer:layer.layer,title:layer.layer.name};
});
if(layerInfo.length > 0){
var legendDijit = new esri.dijit.Legend({
map:map,
layerInfos:layerInfo
},"legendDiv");
legendDijit.startup();
}
});
map.addLayers([waterbodies,rivers]);
This code is from ESRI's sample.
http://help.arcgis.com/en/webapi/javascript/arcgis/jssamples/widget_legend.html
This sample shows only two layers and do not show basemap Layer.
EDITED:
If you are adding DynamicMapServeLayer instead of FeatureLayer and want to control each Layers visibility inside of the MapService, you need to refresh LayerInfo with hideLayers parameter.
//show only index of 0 Layer
//layer is ArcGISDynamicMapServiceLayer object
layer.setVisibleLayers([0]);
// get legend dijit
var legendDijit = dijit.byId("legendDiv");
var visibleLayers = layer.visibleLayers;
var layerInfos = layer.layerInfos;
//create hideLayers array from layerInfos which layers are not visible
var hideLayers = [];
for (var i = 0; i < layerInfos.length; i ++) {
var layerInfo = layerInfos[i];
if(visibleLayers.indexOf(layerInfo.id) == -1){
hideLayers.push(layerInfo.id)
}
}
//refresh legend dijit with hideLayers
legendDijit.refresh([{layer:layer, hideLayers:hideLayers}]);
You've defined your layers as baselayers (not overlays) and so you'll want to change overlayadd
to baselayerchange
map.on('overlayadd', function (eventLayer) {
should be
map.on('baselayerchange', function (eventLayer) {
Here's a fork of your original jsFiddle that demonstrates this change -
http://jsfiddle.net/ry9zf/2/
Best Answer
https://www.mapbox.com/mapbox.js/api/v3.1.1/l-mapbox-legendcontrol/ is an example for Mapbox.js which is a different library to Mapbox GL JS.
I'm afraid building the legend is something you need to build, not provided by Mapbox GL JS.
https://www.mapbox.com/assembly/examples/legends/ might help with some of the layout design.