1

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.

2 Answers 2

1

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.

4
  • Thank you. I know that the leaflet ids will change. But from my understanding, the leaflet id will remain constant through out a session. Can you suggest a better approach to find which shapes have been edited by a user and then update them in the DB? Can I add an extra field to the polygon/ layer which corresponds to the db key field? If layer = drawnItems.addLayer(L.polygon(polygon)) then, how can I find the length of the layer._layers field? I am not trying to iterate through layers. (Please dont suggest the foreach loop)
    – codejunkie
    Nov 3, 2016 at 9:35
  • I found this useful --> stackoverflow.com/questions/12188522/…
    – codejunkie
    Nov 3, 2016 at 9:41
  • You should already have the DB ID as a feature property. Add flags or revision counts to the features (again, as properties in the GeoJSON). Nov 3, 2016 at 9:41
  • I tried that and the field gets added to the layer. However, when I debugged the layer in the "draw:edited" event I found that the newly added field was lost.
    – codejunkie
    Nov 3, 2016 at 9:48
0

I solved this. I created a "hashmap" between the database id and the leaflet shapes id (leaflet_id) while loading shapes on the map. Then in the "draw:edited" I found the database id of the object edited by the user with the help of the "key" = leaflet_id. Thus, I was able to save changes made by the user in the same database record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.