Creating a Simple Layer List With The ArcGIS Server Javascript / REST api
In my example, I use Coldfusion, but you could easily adapt this to your langauge of choice. Actually, you could do this with pure javascript, but using something like Coldfusion just makes sense to me - as you will see from this example. Also, lets be clear - I am terrible with javascript - and I'll be the first to admit that. However, there are thousands and thousands of examples out there to help you along.
I'll show you the important parts here, but essentially its broken down into 3 parts. 1. Make a simple REST call to get a list of all the layers in the map service 2. Loop over the results to display the Layer name and a simple check box (with a onclick event) 3. Create the javascript that turns on and off the layers and then refreshes the map
The simple REST call:
are comfortable with. Coldfusion I find to be the most straightforward. --->
<cfset esri = createObject("component","esri")>
<cfset LayerInfo = esri.ServiceInfo('http://snake/ArcGIS/rest/services/pickenscounty/MapServer?f=json')>
<!--- Create the initial list of layers that should be turned on --->
<cfset LayerVisible = ''>
<cfloop query="LayerInfo">
<cfif DEFAULTVISIBILITY eq 'YES'>
<cfset LayerVisible = listAppend(LayerVisible,#ID#)>
</cfif>
</cfloop>
Now display the results of the REST call:
<input type="checkbox" id="#id#" onclick="toggleDynamicVisibility(#id#);"<cfif DEFAULTVISIBILITY eq 'YES'>checked</cfif>>#Name#<br>
</cfoutput>
Lastly, add some javascript functions that will keep track of the layers to turn on and off and then refresh the map:
//I am using a coldfusion variable to populate this array. again, any language can be used here. var dynamiclayerlist = new Array(#LayerVisible#);
function removeItems(array, item) {
var i = 0;
while (i < array.length) {
if (array[i] == item) {
array.splice(i, 1);
} else {
i++;
}
}
return array;
}
function addItems(array, item) {
array.push(item);
}
function toggleDynamicVisibility(layerid) {
if (dynamiclayerlist.indexOf(layerid) != -1){
removeItems(dynamiclayerlist,layerid);
}else{
addItems(dynamiclayerlist,layerid);
}
dynamiclayer.setVisibleLayers([dynamiclayerlist]);
}
</script>
Note that when I make the REST call, I am using a Coldfusion component (CFC). I have included that cfc in the code download (see below for the link or get it here). So, hopefully when you see the finished code you see just how easy it really is.
This simple demo is available to actually try and view here: http://maps.roktech.net/demo/layerlist.cfm. Hopefully I can get some kind of regular series of simple ArcGIS Server javascript and REST api demos going...