1. 程式人生 > >10 地圖新增圖例控制元件

10 地圖新增圖例控制元件

在上述文章中,我們已經為地圖添加了比例尺、鷹眼等控制元件,但還有一個控制元件也是地圖所必需的,那就是圖例控制元件,它顯示當前地圖上新增的所有圖層的圖例(預設效果,可以手動控制顯示單個圖層的圖例),效果如下所示:

具體實現如下:

1 圖例控制元件的實現主要是依據“esri/dijit/Legend”元件,我們先定義兩個div,一個顯示地圖,另一個顯示圖例,然後設定其樣式,如下:

<div id="map"></div>

<div id="legendDiv"></div>

樣式:

#map{

position: absolute;

top: 0;

left: 0;

width: 100%;

height: 100%;

z-index: 10;

}

#legendDiv{

position: absolute;

bottom: -400px;

left: 5%;

width: 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%;

width: 98%;

margin: 1%;

}

#map{

position: absolute;

top: 0;

left: 0;

width: 100%;

height: 100%;

z-index: 10;

}

#legendDiv{

position: absolute;

bottom: -400px;

left: 5%;

width: 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>