如何将完成的多边形点Leaflet.draw保存到MySQL表中

27

我想使用leaflet.draw创建区域的轮廓。 我已经成功地完成了这个工作: https://www.mapbox.com/mapbox.js/example/v1.0.0/leaflet-draw/

现在,我想将每个多边形的数据保存到mysql表中。 我对如何导出数据以及应该使用的格式有些困惑。

如果可能的话,我希望将数据返回到mapbox/leaflet地图中,所以像geojson这样的格式可能很好。

8个回答

36

因此,您可以使用draw:created来捕获图层,将其转换为geojson,然后将其字符串化以保存在您的数据库中。 我只做过一次这样的操作,虽然很麻烦但是可行。

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);
});

@Micheal,这在标记的情况下不起作用,并且会抛出错误“无法读取未定义的属性'toGeoJSON'(...)”。请帮我解决一下。 - Hassan Tahir
1
不错,但如何将 shape_for_db 恢复到图层组中? - Andreas

7

如果你想收集坐标,你可以这样做:

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;
};

这个标记无法正常工作,会抛出错误“Cannot read property 'toGeoJSON' of undefined(…)” 请帮我解决。 - Hassan Tahir

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);

在创建时,我们可以将Id设置为新创建的形状,但是在编辑时如何捕获相同的Id以保存更改到数据库? - dawncode

1
获取共享为关联数组 + 圆半径
  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;
    };

1
不要忘记圆的半径。
            if (layer instanceof L.Circle) {
                shapes.push([layer.getLatLng()],layer.getRadius())
            }

PS这个声明可能没有得到适当的格式,但你明白重点。 (或者说半径以及点的位置;-)


1

@Michael Evans的方法如果你想使用GeoJSON应该是可行的。

如果你想为每个形状保存LatLngs点,你可以像这样做:

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
}

0
对我而言,这个适用:
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);
});

0

对我来说,这个方法可行: 获取坐标后,通过ajax将其发送到php文件,然后保存到数据库中

 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(); 
    

使用 AJAX 将代码 enter code here 发送到 PHP 文件

 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'}}});
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接