I am new to JavaScript and Leaflet, so please bear with me. I am working on a Leaflet map in which I am calling in two separate REST layers, a point layer (heritage trees) and polygon layer (neighborhoods), using L.esri.featureLayer. What I would like to do is add functionality to the neighborhood polygon layer in which a popup is displayed with the number of heritage trees that are located within a given neighborhood when it is clicked by the user. Because I am already using the L.esri plugin, I'm trying to do this using the L.esri.query functionality, but can't figure out how to get it to work. Here is the JavaScript I have so far:

//Define neighborhoods feature layer
var nbohoods = L.esri.featureLayer({
minZoom: 12,
opacity: 20,
onEachFeature: function(layer){
    //define trees as query layer
    var trees = L.esri.query({
        url: 'https://www.portlandmaps.com/arcgis/rest/services/Public/COP_OpenData/MapServer/26',

nbohoods.bindPopup(function (layer) {
    return L.Util.template("<p><strong>Neighborhood Name: </strong> {MAPLABEL}</p>", layer.feature.properties 

I know I'm not referencing the results of the function in the popup at the end (I don't know how) and I'm also not sure how to access the geometry of the nbohoods variable. Any ideas for how I can get this to work?


1 Answer 1


You do not need to use the onEachFeature event. Insted, in the bindPopup function, you want to just show a temporary message:

nbohoods.bindPopup(function (layer) {
  // return temporary message while the "queryTrees" function called from the popupopen function runs:
    return L.Util.template('getting tree info ...');

And then you want to setup an event listener for the popupopen event, and this is where you'll kick off your query from. You do this because the popupopen event gives you both the layer/feature clicked and a reference to the open popup.

nbohoods.on('popupopen', function(evt) {
    queryTrees(evt.layer.feature, evt.popup);

Finally, define the queryTrees function that we're using above, that takes in a feature and a reference to the popup. It will do the query then update the popup when the query is complete.

var queryTrees = function(feature, popup) {
  .run(function(error, featureCollection) {
    // this function is called when the query is complete. Update the currently open popup.
    popup.setContent(L.Util.template('Number of Trees: ' + featureCollection.features.length));

Putting it all together, here's a sample with it all working.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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