Search code examples
javageotools

How can i draw a line surrounding all the polygons in a single layer in GeoTools?


I have written some code in Java using the GeoTools (v.22) library that opens a shapefile, takes all the polygons in it and divides them in different FeatureCollections based on a value associated to each; it then creates a layer for every FeatureCollection and adds it to a map, resulting in all the polygons each divided from the others by a black stroke.

how can i draw another colored line surrounding all the polygons in the same layer?


Solution

  • You are looking for the Concave Hull of your features. So first you need to get a GeometryCollection of your features. You can then call Eric Grosso's Concave Hull implementation.

    So something like:

        File f = new File("/home/ian/Data/states/states.shp");
        FileDataStore ds = FileDataStoreFinder.getDataStore(f);
    
        Filter filter = ECQL.toFilter("strEndsWith(\"STATE_NAME\",'a')=true");
        SimpleFeatureCollection collection = ds.getFeatureSource().getFeatures(filter);
        ArrayList<Geometry> geoms = new ArrayList<>();
        try (SimpleFeatureIterator it = collection.features()) {
          while (it.hasNext()) {
            SimpleFeature feature = it.next();
            Geometry geom = (Geometry) feature.getDefaultGeometry();
    
            geoms.add(geom);
          }
        }
        GeometryFactory gf = new GeometryFactory();
        GeometryCollection gc = gf.createGeometryCollection(geoms.toArray(new Geometry[] {}));
        gc = (GeometryCollection) Densifier.densify(gc, 5);
        double threshold = 10;
        ConcaveHull ch = new ConcaveHull(gc, threshold);
        Geometry concaveHull = ch.getConcaveHull();
        System.out.println(gc);
        System.out.println(concaveHull);
    

    Which in this case generates the following map:

    enter image description here

    while a threshold of 1 gives:

    enter image description here