简体   繁体   中英

Convert a newly created polygon to GeoJSON in Leaflet

I create polygons of different sizes by clicking a button in my webapp.

I also add some values inside the object as a nested object, like {properties:{status:'active'}} . Then I run toGeoJSON() method of the polygon and get an object with properties and geometry objects. properties object is empty.

My question is how do I add my values into the object so that they are passed to the GeoJSON object on conversion?

Any "extra" data on your Polygon is lost when a GeoJSON object is created for it. Only the coordinates of the polygon are carried over into the GeoJSON object. See lines 213 and 171 in layer/GeoJSON.js in the Leaflet source. On line 171 you can see that a new object is created and that object has an attribute called "properties" but that properties attribute has nothing to do with any attribute called "properties" on your Polygon.

After creating the GeoJSON object you could copy the properties from your Polygon into the properties object on the GeoJSON object by doing something like the following. However - I'm not sure what, if any, specific meaning the "properties" object has in the GeoJSON specification.

var json = polygon.toGeoJSON();
L.extend(json.properties, polygon.properties)

InPursuits answer definitely worked for me...

var rect = L.rectangle(bounds).toGeoJSON();
L.extend(rect.properties, {
    itemIndex: v.itemIndex
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM