codejunkie codejunkie - 1 year ago 257
Javascript Question

Add existing leaflet polygons to an existing leaflet layer

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

to which newly drawn shapes are added.

Please help.

Answer Source

You have to add your polygons to the drawnItems featureGroup! Let's say var polyLayers = dbArray; is your database array with polygons. First create a feature group with your drawn items e.g: var drawnItems = new L.FeatureGroup(); ans add it to the map: map.addLayer(drawnItems);. Then you simple need to iterate over your database polygons and add them to the drawenItems FeatureGroup:

    for(layer of polyLayers) {

Now the layers are added to the map and editable.

Here goes an EXAMPLE:

    var drawnItems = new L.FeatureGroup();

    var polyLayers = [];

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

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

    // Add the layers to the drawnItems feature group 
    for(layer of polyLayers) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download