The PopupTemplate class is used to define and format the content and title of a Layer or Graphic's Popup. You can format the content of the popup's template using a string, popup elements, FieldInfoFormat properties, or a custom function.
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 popup
object is initialized and the layer's popup
property is set as shown below. The popup template content will display 2010 and 2013 population census data for the clicked county.
// create a new popupTemplate for the layer
const 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.
//'{}' is placeholder to specify attributes to display.
// POP2010 is a numeric field and the values from
// this field will be formatted
const 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 population
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 PO
.
function populationChange (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;
};