前言
控制服务中的图层显隐
思路
通过MapServiceLayer的setVisibleLayers()
方法设置显示的图层的显示
代码实现
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="http://localhost:8080/arcgis_js_api/library/3.20/3.20/dijit/themes/tundra/tundra.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:8080/arcgis_js_api/library/3.20/3.20/esri/css/esri.css" />
<script type="text/javascript" src="http://localhost:8080/arcgis_js_api/library/3.20/3.20/init.js"></script>
<style>
html, body, #map {
height: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #FFF;
overflow: hidden;
font-family: "Trebuchet MS";
}
</style>
<script>
var map,
visible=[],
setLayerVisibility;
require([
"esri/map",
"esri/layers/ArcGISDynamicMapServiceLayer",
"dojo/on",
"dojo/dom",
"dojo/query",
"dojo/dom-attr",
"dojo/domReady!"],
function(Map,
ArcGISDynamicMapServiceLayer,
on,
dom,
query,
domAttr
)
{
map = new Map("map", {
center: [112, 38],
zoom: 5,
basemap: "topo"
});
var dynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer("http://localhost:6080/arcgis/rest/services/firstTest/firstService/MapServer");
map.addLayer(dynamicMapServiceLayer);
on(dynamicMapServiceLayer,"load",loadLayerList);
function loadLayerList(layers){
var html="";
var infos=layers.layer.layerInfos;
for(var i= 0,length=infos.length;i<length;i++){
var info = infos[i];
//图层默认显示的话就把图层id添加到visible
if(info.defaultVisibility)
{
visible.push(info.id);
}
//输出图层列表的html
html=html+"<div><input id='"+info.id+"' name='layerList' class='listCss' type='checkbox' value='checkbox' onclick='setLayerVisibility()' "+(info.defaultVisibility ? "checked":"")+" />"+info.name+"</div>";
}
//设置可视图层
dynamicMapServiceLayer.setVisibleLayers(visible);
//在右边显示图层名列表
domAttr.set(dom.byId("toc"),"innerHTML",html);
// dom.byId("toc").innerHTML=html;
}
setLayerVisibility = function()
{
//用query获取css为listCss的元素数组
var inputs = query(".listCss");
visible = [];
//对checkbox数组进行变量把选中的id添加到visible
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].checked)
{
visible.push(inputs[i].id);
}
}
//设置可视图层
dynamicMapServiceLayer.setVisibleLayers(visible);
}
});
</script>
</head>
<body>
<div id="map">
<div id="toc" style="position: absolute; left: 10px; bottom: 20px; border: 1px solid #9c9c9c; background: #fff; width: 100px; height: auto; z-index: 99;padding: 10px;"></div>
</div>
</body>
</html>