如何使用Leaflet编辑加载的geoJson

时间:2016-05-21 12:07:03

标签: javascript leaflet leaflet.draw

我想从数据库中检索多边形数据,然后进行编辑。我可以检索多边形(存储为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;
        }); 
    }

1 个答案:

答案 0 :(得分:3)

在您的示例中,您需要解析收到的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
   });
});