26

I would like to use leaflet.draw to create outlines of regions. I have managed to get this working ok: https://www.mapbox.com/mapbox.js/example/v1.0.0/leaflet-draw/

Now I'd like to save the data for each polygon to a mysql table. Am a little stuck on how I would go about exporting the data and the format I should be doing it in.

If possible I'd like to pull the data back into a mapbox/leaflet map in the future so guess something like geojson would be good.

metasequoia
  • 7,014
  • 5
  • 41
  • 54
user3703511
  • 261
  • 1
  • 3
  • 3

8 Answers8

36

So you could use draw:created to capture the layer, convert it to geojson then stringify it to save in your database. I've only done this once and it was dirty but worked.

map.on('draw:created', function (e) {
  var type = e.layerType;
  var layer = e.layer;

  var shape = layer.toGeoJSON()
  var shape_for_db = JSON.stringify(shape);
});
Michael Evans
  • 389
  • 2
  • 5
7

If you want to collect the coordinates, you can do it this way:

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

map.on('draw:created', function (e) {

    var type = e.layerType,
        layer = e.layer;

    drawnItems.addLayer(layer);

    var shapes = getShapes(drawnItems);

    // Process them any way you want and save to DB
    ...

});

var getShapes = function(drawnItems) {

    var shapes = [];

    drawnItems.eachLayer(function(layer) {

        // Note: Rectangle extends Polygon. Polygon extends Polyline.
        // Therefore, all of them are instances of Polyline
        if (layer instanceof L.Polyline) {
            shapes.push(layer.getLatLngs())
        }

        if (layer instanceof L.Circle) {
            shapes.push([layer.getLatLng()])
        }

        if (layer instanceof L.Marker) {
            shapes.push([layer.getLatLng()]);
        }

    });

    return shapes;
};
martynas
  • 12,120
  • 3
  • 55
  • 60
  • this does not work in case of marker and throws an error Cannot read property 'toGeoJSON' of undefined(…) Please help me out – Hassan Tahir Nov 11 '16 at 21:15
2
map.on('draw:created', function (e) {
  var type = e.layerType;
  var layer = e.layer;

  var shape = layer.toGeoJSON()
  var shape_for_db = JSON.stringify(shape);
});

// restore
L.geoJSON(JSON.parse(shape_for_db)).addTo(mymap);
Lin Vic
  • 21
  • 1
  • under create we can set the Id to newly create shape but how do we capture the same id when edit to save changes to db – dawncode May 12 '19 at 12:24
1

@Michael Evans method should work if you want to use GeoJSON.

If you want to save LatLngs points for each shape you could do something like this:

map.on('draw:created', function (e) {
    var type = e.layerType;
    var layer = e.layer;
    var latLngs;

    if (type === 'circle') {
       latLngs = layer.getLatLng();
    }
    else
       latLngs = layer.getLatLngs(); // Returns an array of the points in the path.

    // process latLngs as you see fit and then save
}
pk.
  • 956
  • 7
  • 13
1

Don't forget the radius of the circle

            if (layer instanceof L.Circle) {
                shapes.push([layer.getLatLng()],layer.getRadius())
            }

PS that statement may not get the proper formatting but you see the point. (Or rather the radius as well as the point ;-)

bds
  • 61
  • 1
  • 1
1

Get shares as associative array + circle radius

  map.on('draw:created', function (e) {
        var type = e.layerType,
                layer = e.layer;

        if (type === 'marker') {
            layer.bindPopup('Call Point!');
        }

        drawnItems.addLayer(layer);

        var shapes = getShapes(drawnItems);

        console.log("shapes",shapes);




    });


    var getShapes = function (drawnItems) {

        var shapes = [];
        shapes["polyline"] = [];
        shapes["circle"] = [];
        shapes["marker"] = [];

        drawnItems.eachLayer(function (layer) {

            // Note: Rectangle extends Polygon. Polygon extends Polyline.
            // Therefore, all of them are instances of Polyline
            if (layer instanceof L.Polyline) {
                shapes["polyline"].push(layer.getLatLngs())
            }

            if (layer instanceof L.Circle) {
                shapes["circle"].push([layer.getLatLng()])
            }

            if (layer instanceof L.Marker) {
                shapes["marker"].push([layer.getLatLng()],layer.getRadius());
            }

        });

        return shapes;
    };
Naumche Ivanovski
  • 110
  • 1
  • 1
  • 6
0

For me it worked this:

map.on(L.Draw.Event.CREATED, function (e) {
    map.addLayer(e.layer);
    var points = e.layer.getLatLngs();
  puncte1=points.join(',');
  puncte1=puncte1.toString();
  //puncte1 = puncte1.replace(/[{}]/g, '');
  puncte1=points.join(',').match(/([\d\.]+)/g).join(',')
//this is the field where u want to add the coordinates
$('#geo').val(puncte1);
});
bicanul123
  • 427
  • 7
  • 21
0

For me it worked this: after get coordinates send to php file with ajax then save to db

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

// Set the title to show on the polygon button
L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a  polygon!';

var drawControl = new L.Control.Draw({
    position: 'topright',
    draw: {
        polyline: true,
        polygon: true,
        circle: true,
        marker: true
    },
    edit: {
        featureGroup: drawnItems,
        remove: true
    }
});
map.addControl(drawControl);

map.on(L.Draw.Event.CREATED, function (e) {
    var type = e.layerType,
        layer = e.layer;
        

    if (type === 'marker') {
        layer.bindPopup('');
    }

    drawnItems.addLayer(layer);
   shape_for_db = layer.getLatLngs(); 
    

SEND TO PHP FILE enter code hereWITH AJAX

 var form_data = new FormData();
            form_data.append("shape_for_db",shape_for_db);
            form_data.append("name", $('#nameCordinate').val());

        $.ajax({
            url: 'assets/map_create.php', // point to server-side PHP script
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (php_script_response) {
                 var tmp = php_script_response.split(',');
                    alert(tmp );
            }
        });
});

map.on(L.Draw.Event.EDITED, function (e) {
    var layers = e.layers;
    var countOfEditedLayers = 0;
    layers.eachLayer(function (layer) {
        countOfEditedLayers++;
    });
    console.log("Edited " + countOfEditedLayers + " layers");
});

L.DomUtil.get('changeColor').onclick = function () {
    drawControl.setDrawingOptions({rectangle: {shapeOptions: {color: '#004a80'}}});
};
Sully
  • 392
  • 4
  • 14