7

I have a bunch of polygons which are stored in a database. I would like to add them to the map in such a way that they can be edited using the leaflet-draw toolbar. Although, now the polygons get added to the map, I am unable edit them.

I think this is because they are not added to the layerGroup() to which newly drawn shapes are added.

Please help.

Manuel
  • 2,334
  • 4
  • 20
  • 36
codejunkie
  • 908
  • 2
  • 21
  • 34

1 Answers1

16

You have to add your polygons to the featureGroup drawnItems ! Let's say,

    var polyLayers = dbArray;

is your database array with polygons. First create a feature group with your drawn items:

    var drawnItems = new L.FeatureGroup();

and add it to the map:

    map.addLayer(drawnItems);

Then you simply need to iterate over your polygons from your database and add them to the drawnItems FeatureGroup:

    for(layer of polyLayers) {
        drawnItems.addLayer(layer); 
    };

Now the layers are added to the map and editable.

Here goes an EXAMPLE:

    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    var polyLayers = [];

    var polygon1 = L.polygon([
        [51.509, -0.08],
        [51.503, -0.06],
        [51.51, -0.047]
    ]);
    polyLayers.push(polygon1)

    var polygon2 = L.polygon([
        [51.512642, -0.099993],
        [51.520387, -0.087633],
        [51.509116, -0.082483]
    ]);
    polyLayers.push(polygon2)

    // Add the layers to the drawnItems feature group 
    for(let layer of polyLayers) {
        drawnItems.addLayer(layer); 
    }
Sebastian
  • 1,321
  • 9
  • 21
Manuel
  • 2,334
  • 4
  • 20
  • 36
  • Adding on to this question. I would like to save shapes that have been edited by the user into the DB. Should I just do a brute force search comparing latlngs with their previous values in the "draw:edited" event or is there a better method? – codejunkie Nov 03 '16 at 04:09
  • Don't do it on draw edited, instead `draw:edited` enable or show a save button, then when save is clicked perform your save logic. I don't bother comparing I force overwrite, but for complex maps you wouldn't want to do it on every change. I guess you could also use a debounce routine... but for some users and changes the save to the database will take longer than their next edit to the shape. – Chris Schaller Oct 06 '21 at 05:22