簡體   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