描述
本例循环地图服务里的所有图层并增加每个图层到一个带checkbox的列表,checkbox能设置图层的显示或隐藏。动态创建列表的优势是所有的图层都会包含在列表中,即使服务器管理员删除或增加了图层。如果不想包含所有图层,仅仅要一个子集,见示例 Explicitly create layer list。
注意本例在建立图层列表以前检查图层是否被完全加载。
函数buildLayerList()循环访问每个图层并作为一个HTML checkbox加入列表。该函数建立了一个图层列表。默认每个图层的可见行被保存在列表中。
每当某人选择或不选checkbox,函数updateLayerVisibility()被调用。 函数循环访问列表中的每个图层,记录哪些图层是可见的数组,然后调用 ArcGISDynamicMapServiceLayer.setVisibleLayers()方法。地图服务里的地图数组可以通过这个方法被设置。
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 3 <html> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 6 <meta http-equiv="X-UA-Compatible" content="IE=7" /> 7 <title>动态创建图层列表</title> 8 <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit/themes/tundra/tundra.css"> 9 <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.6"></script> 10 <script type="text/javascript"> 11 dojo.require("esri.map"); 12 13 var dynamicMapServiceLayer,map,visible = []; 14 15 function init() { 16 map = new esri.Map("map"); 17 18 dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer( 19 "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer" 20 ); 21 22 if (dynamicMapServiceLayer.loaded) { 23 buildLayerList(dynamicMapServiceLayer); 24 }else{ 25 dojo.connect(dynamicMapServiceLayer,"onLoad",buildLayerList); 26 } 27 } 28 29 function buildLayerList(layer) { 30 var infos = layer.layerInfos, info; 31 var items = []; 32 for (var i=0,j=infos.length;i<j;i++) { 33 info = infos[i]; 34 if (info.defaultVisibility) { 35 visible.push(info.id); 36 } 37 items[i] = "<input type='checkbox' class='list_item' checked='" + (info.defaultVisibility ? "checked" : "") + "' id='" + info.id +"' onclick='updateLayerVisibility();'/><label for='" +info.id+ "'>" +info.name+ "</label>"; 38 } 39 dojo.byId("layer_list").innerHTML = items.join(); 40 41 layer.setVisibleLayers(visible); 42 map.addLayer(layer); 43 44 } 45 46 function updateLayerVisibility() { 47 var inputs = dojo.query(".list_item"), input; 48 visible = []; 49 for (var i=0,j=inputs.length;i<j;i++) { 50 if(inputs[i].checked) { 51 visible.push(inputs[i].id); 52 } 53 } 54 dynamicMapServiceLayer.setVisibleLayers(visible); 55 56 } 57 dojo.addOnLoad(init); 58 59 </script> 60 61 </head> 62 63 <body > 64 This sample loads an ArcGISDynamicMapServiceLayer.<br /> 65 It determines the layers in the map service and presents them as checkboxes that can be used to toggle their visibility.<br /> 66 <br /> 67 Layer List: <span id="layer_list"></span><br /> 68 <br /> 69 <div id="map" class="tundra" style=" 900px;height: 600px;border: 1px solid #000"></div> 70 </body> 71 </html>