如何使用 Leaflet 编辑加载的 geoJson

How to edit loaded geoJson with Leaflet

我想从数据库中检索多边形数据,然后对其进行编辑。我可以检索多边形(存储为 geojson),但不能使它们可编辑。我该怎么做?

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

    var drawControl = new L.Control.Draw({
        edit: {
            featureGroup: drawnItems
        }
    });
    map.addControl(drawControl);

    map.on('draw:created',function(e) {
    e.layer.addTo(drawnItems);
    });

    L.control.layers(baseLayers).addTo(map);    

    var oldPolygon = null;
    function showOnMap(rowid){
    if(oldPolygon != null){
    map.removeLayer(oldPolygon);
    }

    $.get("testdbextract.php?show="+rowid,function(data){
        var newPolygon = L.geoJson(data);
        newPolygon.addTo(drawnItems); // or drawnItems.addLayer(newPolygon);
        oldPolygon = newPolygon;
        }); 
    }

在您的示例中,您需要解析收到的 geojson 数据,创建图层并初始化 drawnItems

为了方便起见,您可以像这样创建一个 GeoJson 图层:

// Create a GeoJson layer without adding it to the map
L.geoJson(geojsonFeatures, {
  onEachFeature: onEachFeature
});

// Take advantage of the onEachFeature callback to initialize drawnItems
function onEachFeature(feature, layer) {
  drawnItems.addLayer(layer);
}

这是一个example

在你的代码中,它可以这样使用

$.get("testdbextract.php?show="+rowid,function(data){
   L.geoJson(data, {
      onEachFeature: onEachFeature
   });
});