简体   繁体   中英

Find leaflet id of the latest layer created in Leaflet

I am adding layers to a layergroup "drawnitems" using the leaflet draw library

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

I need to find the leaflet ID of the layer created using the above code immediately upon it's 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 use leaflet id assigned to each shape and then find the corresponding db entry using some logic in the "draw:edited" event.

Okey to simply get the ID of the latest layer added you can do the following:

    for(layer of polyLayers) {

        drawnItems.addLayer(layer); 
        var leafletId = layer._leaflet_id 
    };

But I think for your approach that would not be the best solution, because leaflet ID are not stable. It would be better to create layer variables dynamically and assign an ID from you database, where the layers are stored. Then you are able to get every layer by it's database ID (eg myPolyLayers[idFromDataBase] ). Just do:

    var myPolyLayers = {};

    for(layer of polyLayers) {

        var id = Math.floor((Math.random() * 500) + 1); // The ID from the database 

        myPolyLayers[id] = layer

        drawnItems.addLayer(layer); 
        //var leafletId = layer._leaflet_id 
    };

    console.log(myPolyLayers[id]) // Get the layer with the ID given before 

In this snippet, the ID where I choosed a random number should be the ID from you database.

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.

var polygon = new L.Polygon([
                [51.51, -0.1],
                [51.5, -0.06],
                [51.52, -0.03]
            ]);
polygon.options.id = 1;
drawnItems.addLayer(polygon);

As simple as get _leaflet_id of your latest layer created, for example as you if I am drawing polygons, for example:

let polygon = L.polygon([<my coords>], {color: 'red'});
// Added this way 
let layer = polygon.addTo(this.drawElementsLayer);
// or this way (is the same)
this.drawElementsLayer.addLayer(polygon);

console.log(panelPolygon._leaflet_id) // n
>> 47 (in my eample case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM