Add option to voronoi to retain properties
So I have a FeatureCollection with (among other data):
geometry: { type: "Point", coordinates: […] },
properties: { id, name ... }
However, when I do voronoiPolygons = turf.voronoi(featureCollection), I find that every Feature in voronoiPolygons has empty properties:
geometry: { type: "Polygon", coordinates: […] }
properties: { }
Is it possible to propagate the Features properties to the polygons generated by this method?
Hi @blayhem
That sounds like a sensible idea.
@stevage can you think of any idea why this might not be doable?
I'm getting close-ish (fingers crossed for the next week) to having an alpha release of v7 which is a fairly big overhaul, so this might be something we can sneak into that,
Cheers
It's not trivial, unfortunately. Basically because of how this works:
- Take Point Features, strip them down to LatLongs
- Pass the LatLongs to D3, get back a set of arrays of LatLongs
- Turn those arrays into Polygon Features
So there isn't a step in the process where we have a single point and its resulting polygon.
OTOH, it's plausible (I haven't checked) that the polygons are in the same order as the input array, which would make mapping properties over straightforward.
I'm also not certain that this should be the default behaviour. You could easily have lots of stuff on the points that doesn't make sense on the polygons.
Thanks for the thoughts @stevage - will need to look into the ordering issue because that could be an easy option.
And yep take your point re it not being default behavior, if we do go down this route I think we'll add an optional param for transferring the properties from the point to the poly.
Ok, I have confirmed that feature order is preserved.
I haven't looked at the new branch yet, and may not get to do so in the next week, but here's the code change required I think:
// Main
var fc = featureCollection(
d3voronoi.voronoi()
.x(function (feature) { return feature.geometry.coordinates[0]; })
.y(function (feature) { return feature.geometry.coordinates[1]; })
.extent([[bbox[0], bbox[1]], [bbox[2], bbox[3]]])
.polygons(points.features)
.map(coordsToPolygon)
);
if (options.keepProperties) {
fc.features.forEach(function (polygon, i) {
polygon.properties = JSON.parse(JSON.stringify(points.features[i].properties));
});
}
return fc;
}
Not tested :)
I'm assuming we want to do a deep clone of the .properties because the alternative could be very surprising and harmful.
suggest the issue title be changed to something like "Add option to voronoi to retain properties" to make it clear this ticket is about voronoi.
I actually think this should be the default behaviour and we don't need an extra option. Other operations in turf retain the properties (eg transformTranslate). If you don't want the properties on the polygons you can either clear them from the points before you pass to voronoi or after you get the results back.