1

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, 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.

Can someone please help me figure this out?

1 Answer 1

0

L.featureGroup() has a toGeoJSON() method you can call to get the GeoJSON for that featureGroup:

var geojsonFromFeatureGroup = featureGroup.toGeoJSON();

But this will just be the same thing that's in your featureCollection variable already. If you want to iterate over each feature in your GeoJSON, you can do so by iterating over the featureCollection.features array that you've already defined.

1
  • Thank you for your response. To add to your answer, I recently learned about a couple of other ways to do the same thing based on my example. I can loop through the "geojson" variable to access its id property: geojson.eachLayer(function (layer) { var id = layer.feature.properties.id; testfunction(id); }); Or, if like in this case, I have a bunch of L.geojson objects inside the featureGroup, I can use this: featureGroup.eachLayer(function (layer) { layer.eachLayer(function (layer) { var id = layer.feature.properties.id; testfunction(id); }); });
    – Raj
    Aug 1, 2016 at 13:13

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.