This sample shows how to populate the content of a PopupTemplate using a function that returns a promise. This function returns a formatted string when a query executes successfully.
The feature layer's PopupTemplate.content is set via the query
function.
// Find the counties layer in the map and set the popup template.
const countiesLayer = map.layers.find((layer) => {
return layer.title === "USA Counties Generalized Boundaries";
});
countiesLayer.outFields = ["*"];
countiesLayer.popupTemplate = {
title: "{NAME}",
content: queryChargingStations
};
When a county is clicked, the query
function executes and its associated data is passed into the function. The function executes a query to return statistics on the county layer. After successfully executing, the function returns string-formatted content for the PopupTemplate per each county feature.
function queryChargingStations(target) {
// Count and types of electric charging stations that intersect the county.
const countLevel1 = new StatisticDefinition({
statisticType: "count",
onStatisticField: "EV_Level1_EVSE_Num",
outStatisticFieldName: "numLevel_1"
});
const countLevel2 = new StatisticDefinition({
statisticType: "count",
onStatisticField: "EV_Level2_EVSE_Num",
outStatisticFieldName: "numLevel_2"
});
const countLevel3 = new StatisticDefinition({
statisticType: "count",
onStatisticField: "EV_DC_Fast_Count",
outStatisticFieldName: "numLevel_3"
});
// Create a query object with the target graphic's geometry and the outStatistics.
const queryObject = new Query({
geometry: target.graphic.geometry,
outFields: ["*"],
spatialRelationship: "intersects",
outStatistics: [countLevel1, countLevel2, countLevel3]
});
// Execute the query with the query object.
return query.executeQueryJSON(queryUrl, queryObject).then((result) => {
const stats = result.features[0].attributes;
// Format the query result for the counties popupTemplate's content.
return (
"<b>" +
(stats.numLevel_1 + stats.numLevel_2 + stats.numLevel_3) +
"</b> electric charging stations intersect the boundary of {NAME}. <br><br>" +
"The number and type of stations: <br>" +
"<ul>" +
"<li> Level 1 Charging Stations (120V, AC): " +
stats.numLevel_1 +
"</li>" +
"<li> Level 2 Charging Stations (240V, AC): " +
stats.numLevel_2 +
"</li>" +
"<li> Level 3 Charging Stations (480V, DC): " +
stats.numLevel_3 +
"</li>" +
"</ul>"
);
});
}
The map displays the population in 2020 of each county in the United States. The counties have been generalized, so some distortion may be noticeable at large scales. Counts of 3 different types of electric charging stations are displayed in the popup.