PopupTemplate - use functions to set content

This device does not support 3D.

View the system requirements for more information.

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, out-of-the-box formatting functions, or a custom function.

This sample demonstrates how to format the content of a PopupTemplate using the out-of-the-box NumberFormat function 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.

 // create a new popupTemplate for the layer
 var popupTemplate = {
   title: "Population in {NAME}",
   content: "As of 2010, the population in this area was <b>{POP2010:NumberFormat}</b> " +
      "and the density was <b>{POP10_SQMI:NumberFormat}</b> sq mi. " +
      "As of 2013, the population here was <b>{POP2013:NumberFormat}</b> " +
      "and the density was <b>{POP13_SQMI:NumberFormat}</b> sq mi. <br/> <br/>" +
      "Percent change is {POP2013:populationChange}"
 };

 layer.popupTemplate = popupTemplate;

Number values are formatted using the out-of-the-box NumberFormat function. This function formats numbers into various patterns using the dojo/number.format method. 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
{POP2010:NumberFormat}

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. Value, key, and data parameters are passed into the function. For this example, the key-value pair is POP2013 field and its respective value. The data parameter contains an attributes object specific to the clicked feature.

populationChange = function (value, key, data) {
  // calculate the population percent change from 2010 to 2013.
  var diff = data.POP2013 - data.POP2010;
  var pctChange = (diff * 100) / data.POP2010;
  var result = diff > 0 ? "images/up.png" : "images/down.png";

  // add green arrow if the percent change is positive.
  // red arrow for negatice percent change.
  return "<img src='" + result + "'/>" +
  "<span style='color: " +
  (pctChange < 0 ? "red" : "green") + ";'>" +
  number.format(pctChange, { places: 3 }) +
  "%</span>";
}

Sample search results

TitleSample

There were no match results from your search criteria.