Check it out and view the source to see the code in action: ROK ArcGIS Server Table Of Contents Example
How it works: A function named "addToTOC" takes in two parameters. Layers is the actual layer being added to the map, and listLayers is a Boolean value that will either list the layers in the service or just at the layer at the root of the TOC.
The function checks to make sure the layer has been loaded to the map. If it has not been loaded, it adds an "onLoad" listener to the layer.
After confirming the layer has been added to the map, the layer is passed to one of two functions depending on the value of the listLayers parameter.
Adds the layer to the root of the TOC and lists the sublayers in that service. These layers can then be turned on or off. The method is good for multilayer caches or dynamic services.
Only adds the layer to the root of the TOC. This method is good for layers hosted by ESRI and fused cache layers.
There are three functions that interact w/ the table of contents once it has been created:
Zooms to the full extent of the service
Turns a service on or off
Turns layer in a service on or off
Extra - Transparency Slider:
we have also added a transparency slider that works with the layers
added to the map. As you switch layers from the pulldown list, the
slider value is updated to the current opacity of the layer. This is
Alphabetically adds the layer to the transparency pull down list
Updates the global variable that stores the transparency layer id and sets the slider to the opacity of the layer
Updates the opacity of the layer
We have found these functions to be quite useful, so we thought we would share these with the rest of the community. We hope you find them as useful as we do. If you have any trouble with them, post in the comments.Enjoy.