2

I have several geojsons which contain polygons. But the polygons are reaching over other geojsons. When I import them into lets say Qgis, the polygons, which are distributed among several geojsons are dissected. I need to merge these geojsons into one geojson and the polygons must be recognized and and merged correctly too. I would be happy about a java-solution (like geotools)

  • 1
    Then you should add GeoTools in your tags to raise concern on GeoTools experts. – Germán Carrillo Jan 27 '15 at 14:19
  • ah right, thanks. I would also try other solutions though – Selphiron Jan 27 '15 at 14:23
2

You can read in all the GeoJSON files and then loop through the polygons and select all from the collection that touch or intersect the current one, then merge the selected ones and repeat until no more touch.

So something like this should do it:

GeometryFactory gf = new GeometryFactory();
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
List<SimpleFeature> results = new ArrayList<>();
try (SimpleFeatureIterator itr = col.features()) {
  while (itr.hasNext()) {
    SimpleFeature f = itr.next();

    Filter tFilter = ff.touches(ff.property(f.getDefaultGeometryProperty().getName()),
        ff.literal(f.getDefaultGeometry()));
    Filter iFilter = ff.intersects(ff.property(f.getDefaultGeometryProperty().getName()),
        ff.literal(f.getDefaultGeometry()));
    Or filter = ff.or(tFilter, iFilter);
    SimpleFeatureCollection selection = col.subCollection(filter);
    List<Geometry> geometries = new ArrayList<>();
    try (SimpleFeatureIterator it2 = selection.features()) {
      while (it2.hasNext()) {
        SimpleFeature f2 = it2.next();
        geometries.add((Geometry) f2.getDefaultGeometry());
      }
    }
    GeometryCollection geometryCollection = (GeometryCollection) gf.buildGeometry(geometries);

    Geometry union = geometryCollection.union();
    f.setDefaultGeometry(union);
    results.add(f);
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.