繁体   English   中英

查找在传单中创建的最新图层的传单ID

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

我正在使用传单绘制库将图层添加到图层组“drawnitems”

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

我需要在创建后立即找到使用上述代码创建的层的传单 ID。 这发生在一个循环中。 我正在添加多个图层。

我的目标是将用户编辑过的形状保存到数据库中。 这些形状是预先创建的,然后存储在数据库中,然后在地图上呈现。 为此,我计划使用分配给每个形状的传单 ID,然后使用“draw:edited”事件中的一些逻辑找到相应的 db 条目。

好的,只需获取添加的最新图层的 ID,您可以执行以下操作:

    for(layer of polyLayers) {

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

但是我认为对于您的方法来说这不是最佳解决方案,因为传单 ID 不稳定。 最好动态创建图层变量并从存储图层的数据库中分配一个 ID。 然后你就可以通过它的数据库 ID 获取每一层(例如myPolyLayers[idFromDataBase] )。 只需这样做:

    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 

在这个片段中,我选择随机数的 ID 应该是你数据库中的 ID。

我解决了这个问题。 在地图上加载形状时,我在数据库 id 和传单形状 id (leaflet_id) 之间创建了一个“哈希图”。 然后在“draw:edited”中,我在“key”=leaflet_id的帮助下找到了用户编辑的对象的数据库ID。 因此,我能够将用户所做的更改保存在同一数据库记录中。

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

就像获取_leaflet_id的最新图层的_leaflet_id一样简单,例如,如果我正在绘制多边形,例如:

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).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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