Leaflet Draw not taking properties when converting FeatureGroup to GeoJson

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 13:54:57
ghybs

iH8's initial answer was almost correct.

To specify properties that will appear in a vector layer's GeoJSON export (i.e. through its .toGeoJSON() method), you have to fill its feature.type and feature.properties members:

var myVectorLayer = L.rectangle(...) // whatever

var feature = myVectorLayer.feature = myVectorLayer.feature || {};
feature.type = "Feature";
feature.properties = feature.properties || {};
feature.properties["Foo"] = "Bar";

Now myVectorLayer.toGeoJSON() returns a valid GeoJSON feature object represented by:

{
  "type": "Feature",
  "properties": {
    "Foo": "Bar"
    // More properties that may be pre-filled.
  },
  "geometry": // The vector geometry
}
iH8

A (kind of ugly workaround) is using a L.GeoJSON layer and add the drawn layer's GeoJSON to it by using it's addData method. Afterwards grab the last layer in the L.GeoJSON layer's _layers object. At that point the layer has a valid GeoJSON feature property you can edit:

var geojson = new L.GeoJSON().addTo(map);

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

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

    geojson.addData(e.layer.toGeoJSON());

    var layers = geojson._layers,
        keys = Object.keys(layers),
        key = keys[keys.length - 1],
        layer = layers[key];

    layer.feature.properties = {
        'Foo': 'Bar'
    };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!