This sample demonstrates how to format the content of a PopupTemplate by setting the fieldInfos of the PopupTemplate in addition to a custom function.
How it works
When the application starts, the popupTemplate object is initialized and the layer's popupTemplate property is set as shown below. The popup template content will display 2010 and 2013 population census data for the clicked county.
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
// create a new popupTemplate for the layerconst popupTemplate = {
title: "Population in {NAME}",
content: populationChange
};
layer.popupTemplate = popupTemplate;
Number values are formatted using FieldInfoFormat properties. In this sample, the numbers are formatted using culturally appropriate patterns for representing group (thousands) and decimal separators.
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//'{}' is placeholder to specify attributes to display.// POP2010 is a numeric field and the values from// this field will be formattedconst popupTemplate = {
// autocasts as new PopupTemplate()title: "Population in {NAME}",
content: populationChange,
fieldInfos: [{
fieldName: "POP2010",
format: {
digitSeparator: true,
places: 0 }
},{
fieldName: "POP10_SQMI",
format: {
digitSeparator: true,
places: 2 }
},{
fieldName: "POP2013",
format: {
digitSeparator: true,
places: 0 }
},{
fieldName: "POP13_SQMI",
format: {
digitSeparator: true,
places: 2 }
}]
};
The population percentage change is calculated and the content will display a red down arrow if the percent rate is negative and a green up arrow if the percent rate is positive. Percentage change formatting is done in the populationChange() function. When the feature is clicked, this function is called. The feature is passed into the function. For this example, the feature attribute field value is POP2013.
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
functionpopulationChange (feature) {
// calculate the population percent change from 2010 to 2013.const diff = feature.graphic.attributes.POP2013 - feature.graphic.attributes.POP2010;
const pctChange = (diff * 100) / feature.graphic.attributes.POP2010;
const arrow = diff > 0 ? upArrow : downArrow;
// add green arrow if the percent change is positive.// red arrow for negative percent change. div.innerHTML =
"As of 2010, the total population in this area was <b>"+feature.graphic.attributes.POP2010+"</b> and the density was <b>"+feature.graphic.attributes.POP10_SQMI+"</b> sq mi. As of 2013, the total population was <b>"+feature.graphic.attributes.POP2013+"</b> and the density was <b>"+feature.graphic.attributes.POP13_SQMI+"</b> sq mi. <br/> <br/>" +
"Percent change is " +
arrow +
"<span style='color: " +
(pctChange < 0 ? "red" : "green") +
";'>" +
pctChange.toFixed(3) +
"%</span>";
return div;
};