Hide Table of Contents
Latest Samples
Image Layers
Label Layer

Description

Add client side labels for vector features using the LabelLayer class. Visit theLabeling features client-sidetutorial for more information.


Code

<!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></title>
    <link rel="stylesheet" href="//js.arcgis.com/3.9/js/esri/css/esri.css">
    <style>
      html, body, #map {
        height: 100%; width: 100%; margin: 0; padding: 0; 
      }
    </style>

    <script src="//js.arcgis.com/3.9/"></script>
    <script>
      var map;
    
      require([
        "esri/map", 
        "esri/geometry/Extent",
        "esri/layers/FeatureLayer",

        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/symbols/TextSymbol",
        "esri/renderers/SimpleRenderer",

        "esri/layers/LabelLayer",

        "esri/Color",
        "dojo/domReady!"
      ], function(
        Map, Extent, FeatureLayer,
        SimpleLineSymbol, SimpleFillSymbol, TextSymbol, SimpleRenderer,
        LabelLayer,
        Color
      ) {
        // load the map centered on the United States
        var bbox = new Extent({"xmin":-1940058,"ymin":-814715,"xmax":1683105,"ymax":1446096,"spatialReference":{"wkid":102003}});
        map = new Map("map", {
          extent: bbox
        });

        var labelField = "STATE_NAME";

        // create a renderer for the states layer to override default symbology
        var statesColor = new Color("#666");
        var statesLine = new SimpleLineSymbol("solid", statesColor, 1.5);
        var statesSymbol = new SimpleFillSymbol("solid", statesLine, null);
        var statesRenderer = new SimpleRenderer(statesSymbol);
        // create a feature layer to show country boundaries
        var statesUrl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3";
        var states = new FeatureLayer(statesUrl, {
          id: "states",
          outFields: [labelField] 
        });
        states.setRenderer(statesRenderer);
        map.addLayer(states);

        // create a text symbol to define the style of labels
        var statesLabel = new TextSymbol().setColor(statesColor);
        statesLabel.font.setSize("14pt");
        statesLabel.font.setFamily("arial");
        statesLabelRenderer = new SimpleRenderer(statesLabel);
        var labels = new LabelLayer({ id: "labels" });
        // tell the label layer to label the countries feature layer 
        // using the field named "admin"
        labels.addFeatureLayer(states, statesLabelRenderer, "${" + labelField + "}");
        // add the label layer to the map
        map.addLayer(labels);
      });
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>