Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

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); 
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.