[GIS] How to get the TOC to update after adding a new Layer in the ESRI JSAPI

arcgis-javascript-apijavascripttable of contents

I am developing an Web map with the ESRI's JavaScript API v 3.9.

I am using the TOC widget available at http://www.arcgis.com/home/item.html?id=9b6280a6bfb0430f8d1ebc969276b109

The documentation shows how you can initialize the TOC when creating the map. In my case, the user can dynamically add any ArcGIS Dynamic Mapservice by providing the URL.

I have tried the following:

  1. Add the Layer to the toc's layerInfos and then calling toc.startup(); This does not do anything. Neither is there an error, nor do I see the new layer.
  2. Delete the HTML inside the TOC Div, and try to recreate the widget with the new layerInfos. This gives me an error saying that the div has already been registered.

How do I show this new Layer in the TOC when it is already initialized?

Best Answer

There is a simple way to do this.

  • Add the new layer to the toc's layerInfos like this:

    toc.layerInfos.push({"layer": newLayer, "title": "New Layer"});

  • Refresh the TOC with the following code:

    toc.refresh();