Leaflet 在传单中加载时向geojson功能添加ID

Leaflet 在传单中加载时向geojson功能添加ID,leaflet,Leaflet,我正在将geojson图层加载到传单地图中。我想根据geojson中存储的属性设置svg元素的ID 我假设我使用了onEachFeature函数,但我看不到如何在解析时设置特性的ID 如何分配元素的ID?可以,但不能使用L.GeoJSON的onEachFeature方法。这是因为: var geoJsonLayer = L.geoJson(null, { onEachFeature: function (feature, layer) { // At this point

我正在将geojson图层加载到传单地图中。我想根据geojson中存储的属性设置svg元素的ID

我假设我使用了onEachFeature函数,但我看不到如何在解析时设置特性的ID


如何分配元素的ID?

可以,但不能使用
L.GeoJSON
onEachFeature
方法。这是因为:

var geoJsonLayer = L.geoJson(null, {
    onEachFeature: function (feature, layer) {
        // At this point 'layer._path' exists in the layer object
        // but it will return as 'undefined' so this is of no use
        // So the following doesn't work:
        layer._path.id = 'feature-' + feature.properties.id
    }
});
但是,如果使用
L.GeoJSON
中的
eachLayer
方法,
层。_path
将返回实际的SVG路径元素,但只有在将GeoJSON层添加到地图后才会执行此操作。如果在将图层添加到地图
图层之前执行此操作,_path
仍将返回为
undefined
。所以试试这个:

var geoJsonLayer = L.geoJson(data).addTo(map);

geoJsonLayer.eachLayer(function (layer) {
    layer._path.id = 'feature-' + layer.feature.properties.id;
});

这里有一个关于Plunker的工作示例:

太棒了!工作起来很有魅力。其他人需要注意的是,在我的实现中,我必须在赋值之前检查变量是否已定义,因为我正在通过一些没有路径的额外特性。谢谢所以我发现额外的特征是多个多边形,我用上面的解决方案跳过了它们。相反,您需要迭代多多边形功能的每一层。因此,使用类比我最初的问题所提出的id更合适<代码>如果(层的类型._path!=“undefined”){layer._path.id=layer.feature.properties.id;}否则{layer.eachLayer(函数(layer2){layer2._path.id=layer.feature.properties.id;}