AnsweredAssumed Answered

What to do if I just want to display a single layer's legend?

Question asked by steven.lzhou on Jan 20, 2014
Latest reply on Jan 23, 2014 by steven.lzhou
I want to add a legend, it works when I add several layers together.  But when I want to add just a single layer, I make the code as the following:
var legendLayer = [];               map.on("layer-add-result", function (evt) {                    legendLayer.push({ layer: Layer1, title: 'AAABBC' });                    var legendDijit = new Legend({                       map: map,                       layerInfos: legendLayer                   }, "legendDiv");                   legendDijit.startup();                 });               map.addLayer(Layer1);


Everytime I change a basemap or scroll the mouse wheel, it adds the extra same legend to the legend pane.  When I add multi-layers, using the following code it always works, I just change the "layers-add-result" to "layer-add-result", then it does not work. So what should I do if just want to add a single layer? Thanks a lot!

map.on("layers-add-result", function (evt) {                    var layerInfo = arrayUtils.map(evt.layers, function (layer, index) {                       return { layer: layer.layer, title: layer.layer.name };                   });                   if (layerInfo.length > 0) {                       var legendDijit = new Legend({                           map: map,                           layerInfos: layerInfo                       }, "legendDiv");                       legendDijit.startup();                   }               });                map.addLayers([Layer1, Layer2]);   

Outcomes