8.4 ArcGIS Server: Displaying Legends

In this tutorial we will learn how to add legends into the side panel for your ArcGIS Maps.

Startup Code

This tutorial will continue where 8.3 left off. We will be adding a fourth panel to contain our legends.

Creating the Legend Panel Div

First, we need to create the Legend Panel Div. Insert the following code underneath the Find Directions panel to create an empty panel.

1
2
3
4
5
<h3><a href="#">Map Legends</a></h3>
<div>
<!-- display legend -->
<div id="legendPanel"></div>
</div>

Notice that this panel div ID is legendPanel. We will use this ID when we are populating the empty panel with legends.

Creating the getLegend Function

Now let’s create a function to grab legend data from ArcGIS Server. This function will take your map service URL as its only input and will use that URL to retrieve and display map legend information. Add it to your global space:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
yoh.getLegend = function(serviceUrl)
{
    $.getJSON(serviceUrl +'/legend?f=json&callback=?', //{},
        function(data)
        {
        $('#legendPanel').append('<strong>'+data.layers[0].layerName+'</strong><br>');
        $.each(data.layers[0].legend, function(i,item)
        {
            var label = item.label;
            var url = item.url;
            //trace(item.label);
            $('#legendPanel').append('<img src="' + serviceUrl +'/0/images/' +item.url+ '" />');
            $('#legendPanel').append(' ' + item.label + '<br>');
        });
        }
    );
}

Let’s break this function down:

First we’re using the $.getJSON function to query the ArcGIS server for its map legend information.

You’ll notice that the URL that we’re querying is the normal map service rest directory URL with “/legend” appended to the end. Let’s take a closer look at this URL. You can see the legend for your map is displayed here. If you click on the REST link at the bottom, you can see how ArcServer organizes its data.

Next, we use the append function to create the title of the legend based on the name of the data layer.

In the final part of this function, we use the $.each function to loop through each item in array to grab the legend color and label and display it in your side panel.

Finally, remember to call your legends in your initialize function with the following lines of code:

1
2
yoh.getLegend(serviceUrlOne);
yoh.getLegend(serviceUrlThree);

Final Code Sample

Leave a Reply