Warm tip: This article is reproduced from serverfault.com, please click

Leaflet Draw not taking properties when converting FeatureGroup to GeoJson

发布于 2016-03-02 23:14:26

I'm unable to convert my Layer properties into the properties of the GEOJson object using Leaflet(0.7.7)/Leaflet.Draw(latest). My workflow is:

1 Create Map: var map = L.map('#map', options);

2 Create a FeatureGroup: features= new L.FeatureGroup();

3 Add to the Leaflet Map: map.addLayer(features);

4 On the draw:created event, I'm capturing e.layer and adding a bunch of properties:

var layer = e.layer;

layer.properties = { Title: 'Hello' };

features.addLayer(layer);

geo_features = features.toGeoJSON();

However, my geo_features always have empty property attributes in each of the features and I can't figure it out!

Questioner
Chronix3
Viewed
0
2017-05-23 20:33:40

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
}