leafletgeojsonsnappingleaflet-drawleaflet-geoman

Leaflet Draw and Leaflet Snap with geojson polygon layers


I'm trying to enable snapping (using Leaflet Snap)in a Leaflet application I'm creating. I'm using Leaflet Draw. Existing layers are read in from a database in geojson. I add these to the guideLayers and I add newly created features there too. It's not working. Has anyone successfully been able to create something like this? That is, been able to create a new polygon and snap to existing polygons in leaflet (geojson layers)? Thanks Dan.

Add geojson to guideLayers code:

function renderLta(_ltas,ltaLayerName) {

L.geoJSON([_ltas.geoJson], {
        name:_ltas.id,
        areaName:_ltas.localThreatAreaName,
        areaDescription:_ltas.localThreatAreaDescription,
        style: function (feature) {
        return _getLtaStyle(1);         
        },      
        onEachFeature: function onEachFeature(feature, layer) {
            ltaLayerName.addLayer(layer);
            guideLayers.push(layer);
            layer.on('click', function(e) {
                if(selectedFeature) {
                    selectedFeature.editing.disable();
                    // Has there been a change? Does the user need to save?
                    // get layer again and redraw
                       drawnItems.removeLayer(selectedFeature);
                       selectedFeature.addTo(map_lta);
                }
                selectedFeature = e.target;
                e.target.editing.enable();
                drawnItems.addLayer(e.target);                              
            });             
        }       
       });

        ltaLayerName.addTo(map);

Add new layer/data to guideLayers code:

        map.on(L.Draw.Event.CREATED, function(event) {
        var layer = event.layer;
        var content = getPopupContent(layer);
        if (content !== null) {
            layer.bindPopup(content);
        }
        drawnItems.addLayer(layer);
        guideLayers.push(layer);
        });

DrawControl Code:

var drawControl = new L.Control.Draw({
        edit: {
            featureGroup: drawnItems,
            poly : {
                allowIntersection : false
            }
        },
        draw: {
            polyline: false,
            polygon : { showArea: true, allowIntersection : false, guideLayers: guideLayers, snapDistance: 500 },
            circle: false,
            rectangle: false,
            marker: false,
            circlemarker: false
        }
    });

    map_lta.addControl(drawControl);

    drawControl.setDrawingOptions({
        polygon: { guideLayers: guideLayers, snapDistance: 50 },
   });

Solution

  • You can use the following library to draw and snap https://www.npmjs.com/package/@geoman-io/leaflet-geoman-free packages

    and for more functionalities which are not present in above mentioned package you can use this one especially for polylines https://www.npmjs.com/package/leaflet-linestring-editor