3

I have a need to implement labels on features in a FeatureLayer in version 3.5 if Esri's Javascript API. The labels are from a field returned by a REST feature service. I can't move to 3.7 for various reasons at this time. I have tried using a TextSymbol but my map features just turn to the color of the TextSymbol and no text appears. I may be approaching this in he wrong manner, though. Below is the code I'm attempting to use for labeling with the featureLayer object being my instance of the FeatureLayer I'm adding to the map. Is there a different or proper way to accomplish this task?

featureLayer.on("graphic-add", function (evt) { 
var labelColor = new Color([255, 0, 0, 0.25]);
var myLabel = new TextSymbol(evt.graphic.attributes["My Field Name"]);
myLabel.setColor(labelColor);
myLabel.font.setSize("14pt");
evt.graphic.setSymbol(myLabel);
//console.log(evt);
});

Thanks for any help that can be provided!

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Oct 19, 2013 at 17:34

1 Answer 1

2

I was able to solve this with the code below. This seems to work great.

var labelList = new Array(); 
featureLayer.on("update-end", function (evt) { 
for (var i = 0; i < evt.target.graphics.length; i++) {
var gfx = evt.target.graphics[i];
//if label hasn't been added go ahead and generate it and add to array
if (labelList.indexOf(gfx.attributes[idField]) == -1) {
labelList.push(gfx.attributes[idField]);
addLabelToGeometry(gfx.attributes[labelField], gfx.geometry);
}
}
});
function addLabelToGeometry(text, geometry) {
var point = geometry.getExtent().getCenter();
//top level label of text
var TextSymbolJson = { 
"type": "esriTS",
"color": [0, 0, 0, 255],
"verticalAlignment": "middle",
"horizontalAlignment": "center",
"font": {
"family": "Helvetica",
"size": 12,
"style": "normal",
"weight": "bold",
"decoration": "none"
}
};
var labelTextSymbol = new esri.symbol.TextSymbol(TextSymbolJson);
labelTextSymbol.setText(text);
var labelGraphic = new esri.Graphic(point, labelTextSymbol);
map.graphics.add(labelGraphic); 
}
answered Oct 20, 2013 at 15:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.