[GIS] Find leaflet id of the latest layer created in Leaflet

leafletleaflet-draw

I am adding layers to a layergroup "drawnitems" in leaflet

drawnItems.addLayer(L.polygon(polygon));

I need to find the leaflet id of the layer created using the above code immediately upon its creation. This happens in a loop. I am adding multiple layers.

My goal is to save shapes that have been edited by the user into the DB. These shapes are previously created and then stored in the DB and then rendered on the map. For this I am planning to using leaflet id assigned to each shape and then find the corresponding db entry using some logic in the "draw:edited" event.

Best Answer

I need to find the leaflet id of the layer created [...]

No, you don't.

I am planning to using leaflet id assigned to each shape and then find the corresponding db entry

What you really want is to assign self-incrementing IDs at the DB level, most likely making that ID a primary key of the DB table. New features get no ID until they get dumped into the DB, existing features piggyback the DB ID when they get displayed/edited.

Leaflet IDs are meant to be internal to Leaflet, as they are unique within the lifetime of a document. Reload the webpage, or close the tab, and all the internal leaflet IDs will change in arbitrary ways and confuse you greatly.