Friday 25 August 2017

Does leaflet support user defined Layer identifiers



It would be nice to be able to check for a layer presence or remove it without having to keep an explicit reference to it. To that extent I would like to use ad id for the layer that I can compute myself from my data. Is this feasible with leaflet? If no, do you have any clean workaround?


For example with a LayerGroup, the idea is to have a setId( id) function that would allow leveraging the native removeLayer( id ) and getLayer( id ) methods to work on the LayerGroup content by user defined identifiers. Example below:


marker = L.circleMarker(...);
marker.setId('my_marker_id');
lg = L.layerGroup(...);
lg.addLayer(marker);
...
lg.removeLayer('my_marker_id');

Answer



If you place all your layers in the same L.featureGroup or L.layerGroup, like this:



group = L.featureGroup().addTo(map);
L.marker([34.07,-118.29]).addTo(group);
L.marker([34.06,-118.28]).addTo(group);
[etc., etc....]

you can iterate over the layers using the .eachLayer method. This will allow you to create a property of any name you like (say, layerID) and assign a unique value to each layer:


var tempID = 1;
group.eachLayer(function(layer) {
layer.layerID = tempID;
tempID+=1;

layer.bindPopup('Layer ID: ' + layer.layerID);
});

To access that ID later, you can use .eachLayer again to find the matching feature and perform whatever task you like on it. For instance:


deleteFromGroupByID = function (group, ID) {
group.eachLayer(function(layer) {
if (layer.feature.properties.layerID === ID) {
group.removeLayer(layer);
}
});

}

Here's an example fiddle of this at work:


http://jsfiddle.net/nathansnider/6aLmzwmg/


If you are using GeoJSON, it is probably best to store this value in the feature properties instead, as that's what they were designed for. In the above code, you'd just replace layer.layerID with layer.feature.properties.layerID. Example:


http://jsfiddle.net/nathansnider/oe61fkg0/


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...