Search code examples
leafletmapboxgeojson

Access geojson property of a layer in a featuregroup in Mapbox


I have a GEOJSON which I added to the featuregroup in my Mapbox map like this:

var featureCollection = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {
      "id": 1
    },
    "geometry": {
      "type": "Point",
      "coordinates": [0, 0]
    }
  },{
    "type": "Feature",
    "properties": {
      "id": 2
    },
    "geometry": {
      "type": "Point",
      "coordinates": [30, 30]
    }
  },{
    "type": "Feature",
    "properties": {
      "id": 3
    },
    "geometry": {
      "type": "Point",
      "coordinates": [-30, -30]
    }
  }]
};
var geojson = L.geoJson(featureCollection);
var featureGroup = L.featureGroup().addTo(map);
featureGroup.addLayer(geojson);

Now, I wish to access the id property of each layer while looping through the featuregroup, so that I can pass it as an argument to another function. In the case of a featurelayer, I can easily access it using something like this:

var featureLayer = L.mapbox.featureLayer(featureCollection).addTo(map);
featureLayer.eachLayer(function (layer) {
  layer.on('click', function (e) {
    console.log('Clicked feature ID: ' + e.target.feature.properties.id);
  });
});

But I want to be able to access it while looping inside a featuregroup, and also I want to be able to do it without a 'click' or any such event. For example, ideally I would use something like this:

featureGroup.eachLayer(function (layer) {
  var id = layer.feature.properties.id;
  testfunction(id);
});

I haven't been able to figure out how to do that. I've tried searching online, but because I'm new to this, I probably haven't been using the right keywords in my search.


Solution

  • geojson is nested within featureGroup, so when your eachLayer function runs, it is not operating on the individual features within geojson, but instead on geojson itself. To extract each feature's id property, you will need to go one level deeper and iterate over the features within geojson.

    Fortunately, the L.GeoJson class also supports the eachLayer method (because it is an extension of L.FeatureGroup, which is itself an extension of L.LayerGroup). To print the id of each feature, you could just use the eachLayer method directly on geojson:

    geojson.eachLayer(function (layer) {
      var id = layer.feature.properties.id;
      testfunction(id);
    });
    

    Or, if you have a bunch of L.GeoJson objects nested within featureGroup, you can use:

    featureGroup.eachLayer(function (layer) {
      layer.eachLayer(function (layer) {
        var id = layer.feature.properties.id;
        testfunction(id);
      });
    });