Change label field for ArcGISDynamicMapServiceLayer

1784
10
08-04-2017 04:09 PM
GareySmiley
New Contributor III

Trying to change the field used for a label in a lay with in a ArcGISDynamicMapServiceLayer layer. Here's what I tried.

var json = {
"labelPlacement":"esriServerPolygonPlacementAlwaysHorizontal"
,"where":null
,"labelExpression":"[States.NAME]"
,"useCodedValues":true
,"symbol":{
"type":"esriTS"
,"color":[0,0,0,255]
,"backgroundColor":null
,"borderLineColor":null
,"borderLineSize":null
,"verticalAlignment":"bottom"
,"horizontalAlignment":"left"
,"rightToLeft":false
,"angle":0
,"xoffset":0
,"yoffset":0
,"kerning":true
,"haloColor":null
,"haloSize":null
,"font":{
"family":"Arial"
,"size": 8
,"style":"normal"
,"weight":"normal"
,"decoration":"none"
}
}
,"minScale":0
,"maxScale":0
};

// create instance of LabelClass
var labelClass = new LabelClass(json);
console.log("labelClass",labelClass);

var layerDrawingOptions = [];
var layerDrawingOption = new esri.layers.LayerDrawingOptions();

var renderer = response.renderer;

layerDrawingOption.renderer = renderer;

layerDrawingOption.showLabels = true;
layerDrawingOption.labelingInfo = labelClass;

// Sets the opacity (transparency) of the layer.
// Values range from 0.0 to 1.0, where 0.0 is 100% transparent and 1.0 has no transparency.
layerDrawingOption.transparency = transparency;

console.log("layerDrawingOption",layerDrawingOption);

layerDrawingOptions[1] = layerDrawingOption;
geoLayer.setLayerDrawingOptions(layerDrawingOptions);

Any ideas would be appreciated. 

0 Kudos
10 Replies
RobertScheitlin__GISP
MVP Emeritus

Garey,

   Here is a full sample for dynamically changing the ArcGISDynamicMapServiceLayer's label field:

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
  <title></title>

  <link rel="stylesheet" href="http://js.arcgis.com/3.15/dijit/themes//tundra/tundra.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.15/esri/css/esri.css">
  <style>
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }

    h3 {
      margin: 0 0 5px 0;
      border-bottom: 1px solid #444;
      text-align: center;
    }

    .shadow {
      -moz-box-shadow: 0 0 5px #888;
      -webkit-box-shadow: 0 0 5px #888;
      box-shadow: 0 0 5px #888;
    }

    #map {
      margin: 0;
      padding: 0;
    }

    #feedback {
      background: #fff;
      color: #444;
      font-family: arial;
      left: 30px;
      margin: 5px;
      padding: 10px;
      position: absolute;
      top: 30px;
      width: 300px;
      z-index: 40;
    }

    #note {
      font-size: 80%;
      font-weight: 700;
      padding: 0 0 10px 0;
    }

    #loading {
      visibility: hidden;
    }

    #legendDiv {
      padding: 10px 0 0 0;
    }
  </style>

  <script src="http://js.arcgis.com/3.15/"></script>
  <script>
    var app = {};
    require([
        "esri/map", "esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/ArcGISDynamicMapServiceLayer",
        "esri/request", "esri/config", "esri/tasks/ClassBreaksDefinition", "esri/tasks/AlgorithmicColorRamp",
        "esri/tasks/GenerateRendererParameters", "esri/tasks/GenerateRendererTask",
        "esri/layers/LayerDrawingOptions", "esri/layers/LabelClass", "esri/symbols/TextSymbol",
        "esri/symbols/SimpleFillSymbol", "esri/dijit/Legend",
        "dojo/parser", "dojo/_base/array", "esri/Color", "dojo/dom-style",
        "dojo/json", "dojo/dom", "dojo/data/ItemFileReadStore", "dijit/registry",
        "dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/form/FilteringSelect",
        "dojo/domReady!"
      ], function (
      Map,
      ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer,
      esriRequest, esriConfig,
      ClassBreaksDefinition, AlgorithmicColorRamp,
      GenerateRendererParameters, GenerateRendererTask,
      LayerDrawingOptions, LabelClass, TextSymbol,
      SimpleFillSymbol, Legend,
      parser, arrayUtils, Color, domStyle,
      JSON, dom,
      ItemFileReadStore,
      registry
    ) {
      parser.parse();

      app.dataUrl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2";
      app.defaultFrom = "#ffffcc";
      app.defaultTo = "#006837";

      app.map = new Map("map", {
        center: [-85.787, 39.782],
        zoom: 9,
        slider: false
      });

      var basemap = new ArcGISTiledMapServiceLayer("http://services.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer");
      app.map.addLayer(basemap);
      var ref = new ArcGISTiledMapServiceLayer("http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Reference_Overlay/MapServer");

      urlDyn = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer";
      usaLayer = new ArcGISDynamicMapServiceLayer(urlDyn, {
        id: "us_counties",
        opacity: 0.7,
        visible: false
      });
      usaLayer.setVisibleLayers([2]);
      app.map.addLayer(usaLayer);

      var countyFields = esriRequest({
        url: app.dataUrl,
        content: {
          f: "json"
        },
        callbackParamName: "callback"
      });
      countyFields.then(function (resp) {
        var fieldNames, fieldStore;

        fieldNames = {
          identifier: "value",
          label: "name",
          items: []
        };
        arrayUtils.forEach(resp.fields.slice(6, 16), function (f) {
          fieldNames.items.push({
            "name": f.name,
            "value": f.name
          });
        });
        fieldStore = new ItemFileReadStore({
          data: fieldNames
        });
        registry.byId("fieldNames").set("store", fieldStore);
        registry.byId("fieldNames").set("value", "POP2007");
      }, function (err) {
        console.log("failed to get field names: ", err);
      });

      usaLayer.on("update-end", function () {
        domStyle.set("loading", "visibility", "hidden");
      });

      registry.byId("fieldNames").on("change", getData);
      registry.byId("fieldNames").set("value", "POP_2007");

      function getData() {
        var optionsArray = [];
        var drawingOptions = new LayerDrawingOptions();
        var labelClass = new LabelClass({
          labelExpression: '[' + (registry.byId("fieldNames").get("value") || "POP2000") + ']',
          labelPlacement: 'esriServerPolygonPlacementAlwaysHorizontal',
          symbol: new TextSymbol()
        });

        drawingOptions.labelingInfo = [labelClass];
        drawingOptions.showLabels = true;

        optionsArray[2] = drawingOptions;
        app.map.getLayer("us_counties").setLayerDrawingOptions(optionsArray);
        app.map.getLayer("us_counties").show();
      }

      function errorHandler(err) {
        console.log("error: ", JSON.stringify(err));
      }
    });
  </script>
</head>

<body class="tundra">
  <div data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutters:false" style="width: 100%; height: 100%; margin: 0;">
    <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'">

      <div id="feedback" class="shadow">
        <h3>Change the Attribute Field Used to Render Data</h3>
        <div id="info">
          <div id="note">
            Note: This sample requires an ArcGIS Server version 10.1 map service to generate a renderer.
          </div>

          <!-- filtering select -->
          <label for="fieldNames">Render based on: </label>
          <select id="fieldNames" name="baseSym" data-dojo-type="dijit/form/FilteringSelect" data-dojo-props="style:'width:200px;'">
          </select>

          <img id="loading" src="http://dl.dropbox.com/u/2654618/loading_black.gif" />

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

        </div>
      </div>
    </div>
  </div>
</body>

</html>
0 Kudos
GareySmiley
New Contributor III

Okay I modeled your example in my app, but my service on the ArcGIS Enterprise server crashes if I have the line

drawingOptions.labelingInfo = [labelClass];

Error: Error exporting map
Code: 500

 

if I change it to

drawingOptions.labelingInfo = labelClass;

The code executes without an error, but the labels are not changed.

I also tried

var labelClasses = [];
labelClasses[geoLayerNumber] = labelClass;
layerDrawingOption.labelingInfo = labelClasses;

without success.

Is there something that needs to be turned on in the layer in the MDX or on the ArcGIS server side to make labels work?

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Garey,

   Yes you need to be sure the rest endpoint reports:

Supports Dynamic Layers: true

0 Kudos
GareySmiley
New Contributor III

It is set to true for the layer.

Any other ideas? I'm running out.

0 Kudos
GareySmiley
New Contributor III

Okay made some progress. had to go back to the MDX and turn off the labels. Otherwise they overrode anything I tried to set as the label.

Issue now is that I can only set the labels to a text column. Nothing shows up if the column is numeric.

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Garey,

   No, I don't have any other suggestions. As you can see the sample works fine so it must have to do with your map service. Have you tried a different one?

0 Kudos
GareySmiley
New Contributor III

See my note before your last response. Think we posted at about the same time.

Any ideas on the issue with numeric columns as label?

Thanks so much for your help by the way. 

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Garey,

   In the sample I provided the field pop2000 is esriFieldTypeInteger  and it works fine...

0 Kudos
GareySmiley
New Contributor III

Okay you are right. It works for esriFieldTypeInteger, and esriFieldTypeString, but not esriFieldTypeDouble columns.

Any idea on how to get esriFieldTypeDouble to work? 

0 Kudos