Jordi Tost
Jordi Tost

Reputation: 109

Group TopoJSON geometries by a given property

Does anyone know if it is possible to group TopoJSON geometries with a given same property in multi-geometries?

For examples, given a TopoJSON with the elevation isolines of an area, this should make possible to group geometries with the same elevation, keeping properties.

I found this in the TopoJSON documentation: https://github.com/mbostock/topojson/blob/master/bin/topojson-group

I tested it using the ID for the different elevations, but the output doesn't preserves the properties (even using the -p parameter).

Upvotes: 0

Views: 183

Answers (1)

Gagan
Gagan

Reputation: 1333

Use topjson.js to convert topojson to geojson features. Then you can group the features based on elevation. You can use geojson-groupby to group based on any attributes then use mutligeojson to combine the geometries to MultiGeometry.

var features = [f1, f2, ..,fn]
var grouped = GeoJSONGroupBy(features, 'properties.elevation');
// grouped is
// {
//   '100': [f1, f3, ..],
//   '200': [f5, f8, f6, ..],
//     ....
// }
var merged = {};   // final output merged with geometry and other attributes
Object.keys(grouped).reduce(function(merged,groupKey) {
  var group = grouped[groupKey];
  var reduced = {
    geomCollection: []
    attributes: {
      elevation: group[0].attributes.elevation,
      length: 0   // any other that you want to include
    }
  };
  group.reduce(function(reduced, cur) {
    reduced.geomCollection.push(cur.geometry);
    reduced.attributes.length += length(cur.geometry); //length functon
  },reduced);
  return {
    type: 'Feature',
    geometry: multigeojson.implode(reduced.geomCollection),
    attributes: reduced.attributes
  }
},merged);

Upvotes: 1

Related Questions