在上述文章中,我们已经为地图添加了比例尺、鹰眼等控件,但还有一个控件也是地图所必需的,那就是图例控件,它显示当前地图上添加的所有图层的图例(默认效果,可以手动控制显示单个图层的图例),效果如下所示:
具体实现如下:
1 图例控件的实现主要是依据“esri/dijit/Legend”组件,我们先定义两个div,一个显示地图,另一个显示图例,然后设置其样式,如下:
<div id="map"></div>
<div id="legendDiv"></div>
样式:
#map{
position: absolute;
top: 0;
left: 0;
100%;
height: 100%;
z-index: 10;
}
#legendDiv{
position: absolute;
bottom: -400px;
left: 5%;
200px;
height: 300px;
z-index: 20;
overflow: auto;
background-color: white;
}
2 要想查看图例的显示效果,我们最好拿自己发布的服务来辅助查看。在此示例我们调用官方的两个服务地址,将它们实例化并加载到底图上查看图例的显示效果(如果不实例化任何图层,仅仅为一个地图添加图列时将毫无意义),代码如下:
加载引用:
require([
"esri/map",
"esri/layers/FeatureLayer",
"esri/dijit/Legend",
"dojo/_base/array",
"dojo/domReady!"
], function(
Map,
FeatureLayer,
Legend,
arrayUtils
) {
});
实例化图层:
var rivers = new FeatureLayer("https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Hydrography/Watershed173811/MapServer/1");
var waterbodies = new FeatureLayer("https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Hydrography/Watershed173811/MapServer/0");
map.addLayers([waterbodies, rivers]);
实例化图例:
var legendDijit = new Legend({
map: map
}, "legendDiv");
legendDijit.startup();
3 至此,一个默认的图例控件已经加载完成,下面是完整代码。
<!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>Map with legend</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.25/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.25/esri/css/esri.css">
<style>
html, body {
height: 97%;
98%;
margin: 1%;
}
#map{
position: absolute;
top: 0;
left: 0;
100%;
height: 100%;
z-index: 10;
}
#legendDiv{
position: absolute;
bottom: -400px;
left: 5%;
200px;
height: 300px;
z-index: 20;
overflow: auto;
background-color: white;
}
</style>
<script src="https://js.arcgis.com/3.25/"></script>
<script>
var map;
require([
"esri/map",
"esri/layers/FeatureLayer",
"esri/dijit/Legend",
"dojo/_base/array",
"dojo/domReady!"
], function(
Map,
FeatureLayer,
Legend,
arrayUtils
) {
map = new Map("map", {
basemap:"topo",
center: [-96.53, 38.374],
zoom: 13
});
var rivers = new FeatureLayer("https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Hydrography/Watershed173811/MapServer/1");
var waterbodies = new FeatureLayer("https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Hydrography/Watershed173811/MapServer/0");
map.addLayers([waterbodies, rivers]);
var legendDijit = new Legend({
map: map
}, "legendDiv");
legendDijit.startup();
});
</script>
</head>
<body>
<div id="map"></div>
<div id="legendDiv"></div>
</body>
</html>