79624815

Date: 2025-05-16 08:58:27
Score: 0.5
Natty:
Report link

https://gis.stackexchange.com/questions/168787/java-library-to-break-up-a-big-polygon-into-many-parts

The above link addresses this issue nicely;

Attached is my implementation

public class GeojsonSplitterUtil {

    private static final double MAX_CELL_DEGREE = 0.5;
    private static final GeometryFactory geometryFactory = new GeometryFactory();


    public static Collection<Geometry> split(Geometry geom, int maxSize) {
        List<Geometry> answer = new ArrayList<>();
        if (size(geom) > maxSize) {
            answer.addAll(subdivide(geom));
        } else {
            answer.add(geom);
        }
        return answer;
    }


    public static Collection<Geometry> split(Geometry geom) {
        return new ArrayList<>(subdivide(geom));
    }


    private static int size(Geometry geom) {
        return geom.getCoordinates().length;
    }


    private static List<Geometry> subdivide(Geometry geom) {
        List<Geometry> result = new ArrayList<>();
        Envelope env = geom.getEnvelopeInternal();

        double minX = env.getMinX();
        double maxX = env.getMaxX();
        double minY = env.getMinY();
        double maxY = env.getMaxY();

        double width = maxX - minX;
        double height = maxY - minY;
        int gridX = (int) Math.ceil(width / MAX_CELL_DEGREE);
        int gridY = (int) Math.ceil(height / MAX_CELL_DEGREE);
        double dx = width / gridX;
        double dy = height / gridY;

        for (int i = 0; i < gridX; i++) {
            for (int j = 0; j < gridY; j++) {
                double cellMinX = minX + i * dx;
                double cellMaxX = minX + (i + 1) * dx;
                double cellMinY = minY + j * dy;
                double cellMaxY = minY + (j + 1) * dy;
                Envelope cellEnv = new Envelope(cellMinX, cellMaxX, cellMinY, cellMaxY);
                Geometry cellBox = geometryFactory.toGeometry(cellEnv);

                try {
                    Geometry intersection = geom.intersection(cellBox);
                    if (!intersection.isEmpty() && intersection.isValid()) {
                        result.add(intersection);
                    }
                } catch (Exception e) {
                    log.error("error...!", e);
                }
            }
        }
        return result;
    }
}
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: HuaJFrame