Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 layerGroup() to which newly drawn shapes are added.

Please help.

like image 654
codejunkie Avatar asked Nov 02 '16 09:11

codejunkie


People also ask

What is Tilelayer in Leaflet?

Used to load and display tile layers on the map, implements ILayer interface.

What is Leaflet FeatureGroup?

Extended LayerGroup that makes it easier to do the same thing to all its member layers: bindPopup binds a popup to all of the layers at once (likewise with bindTooltip ) Events are propagated to the FeatureGroup , so if the group has an event handler, it will handle events from any of the layers.

How do you find the center of a polygon in a Leaflet?

find a way to use the coordinates of a polygon to determine the center of the polygon where the popup will open. call one point of the polygon, then offset the position of the popup. Use an id for each polygon, so each popup knows the box area (polygon) it can be opened in.


1 Answers

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); 
    }
like image 155
Manuel Avatar answered Nov 11 '22 19:11

Manuel