访问 Mapbox 要素组中图层的 geojson 属性

Access geojson property of a layer in a featuregroup in Mapbox

我有一个 GEOJSON,我将其添加到我的 Mapbox 地图中的要素组中,如下所示:

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);

现在,我希望在遍历特征组时访问每一层的 ID 属性,以便我可以将其作为参数传递给另一个函数。对于要素图层,我可以使用如下方式轻松访问它:

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);
  });
});

但我希望能够在功能组内循环时访问它,而且我希望能够在没有 'click' 或任何此类事件的情况下访问它。例如,理想情况下我会使用这样的东西:

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

我还不知道该怎么做。我试过在线搜索,但由于我是新手,我可能没有在搜索中使用正确的关键字。

geojson 嵌套在 featureGroup 中,因此当您的 eachLayer 函数运行时,它不会对 geojson 中的各个功能进行操作,而是对 geojson 本身。要提取每个特征的 id 属性,您需要更深入一层并迭代 geojson.

中的特征

幸运的是,the L.GeoJson class也支持eachLayer方法(因为它是L.FeatureGroup的扩展,它本身就是L.LayerGroup的扩展)。要打印每个功能的 id,您可以直接在 geojson:

上使用 eachLayer 方法
geojson.eachLayer(function (layer) {
  var id = layer.feature.properties.id;
  testfunction(id);
});

或者,如果您有一堆 L.GeoJson 对象嵌套在 featureGroup 中,您可以使用:

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