2
votes

I am loading a geojson layer into a leaflet map. I want to set the svg element's ID according to an attribute stored in the geojson.

I assume I use the onEachFeature function, but I can't see how to set the ID of the feature as it parses.

How do I assign the ID of the element?

1

1 Answers

4
votes

It is possible but not by using the onEachFeature method of L.GeoJSON. This because of the following:

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

However if you use the eachLayer method from L.GeoJSON, layer._path will return the actual SVG path element, however it will do this only after the GeoJSON layer is added to the map. If you do this before adding the layer to the map layer._path will still return as undefined. So try this:

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

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

Here's a working example on Plunker: http://plnkr.co/edit/7IPHrO?p=preview