function clipLegend() {
// STEP 1: BUILD QUERYTASK
var queryURL = 'http://<myserver>/arcgis/rest/services/<myservice>/<layerID>';
var queryTask = new esri.tasks.QueryTask(queryURL);
var query = new esri.tasks.Query();
query.where = "1=1";
query.outFields = ["TYPE"];
query.geometry = map.geographicExtent;
query.returnGeometry = false;
query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
var valList = [];
// run query task
queryTask.execute(query, function(results){
// iterate features in result (visible features) and create a list of unique values
for (r in results.features){
// get feature attributes
var attr = results.features.attributes;
// value
var val = attr['TYPE'];
// add to value list
if (valList.indexOf(val) == -1) {
valList.push(val);
}
}
// done creating value list
// clear Legend table
$('.esriLegendLayer').html('')
// STEP 2: get legend via REST API
$.get('http:/<myserver>/arcgis/rest/services<myservice>/legend?f=json', function(json){
// STEP 3: compare value list to layer legend and select
// label/symbol list
var clipList = [];
for (labels in json['layers']) {
if (json['layers'][labels]['layerId'] == <layerID>){
// legend for layer
var leg = json['layers'][labels]['legend'];
// iterate labels
for (label in leg){
if ('values' in leg[label]) {
// get values for that make up current label symbology
var labelVals = leg[label]['values'];
/// check in which label/symbol category the feature value falls
for (v in valList){
// use only label/symbol categories with a value list
if (labelVals.indexOf(valList) != -1) {
// add unique label value to clip list
if (!(leg[label]['label'] in clipList)) {
clipList[leg[label]['label']] = leg[label]['url'];
}
}
}
}
}
}
}
// STEP 4: rebuild legend table
for (c in clipList){
var url = clipList;
var img = queryURL + '/images/' + url;
$('.esriLegendLayer').append('<tr><td><img src="'+ img +'"></td><td align="left">' + c + '</td></tr>');
}
}, "json");
});
}