
// Polygonize.java
// Martin Davis
// The LocationTech Technology (LTT) Group; Vivid Solutions
// https://github.com/locationtech/jts
// Modified by Andrew Davison, ad@coe.psu.ac.th, March 2023

/* Use Polygonizer to convert lines into polygons.

   Usage:
    > compile Polygonize.java
    > run Polygonize

  When prompted, press <enter> on the command line to move 
  to the next example.
*/

import java.util.*;

import org.locationtech.jts.geom.*;
import org.locationtech.jts.operation.polygonize.Polygonizer;


public class Polygonize
{

  public static void main(String[] args)
  {
    GeomsViewer gv = Utils.view("Polygonize");

    List<Geometry> lines = new ArrayList<>();
    lines.add( Utils.toGeometry("LINESTRING (0 0, 10 10)"));   // isolated line
    lines.add( Utils.toGeometry("LINESTRING (185 221, 100 100)"));   // unused line
    lines.add( Utils.toGeometry("LINESTRING (185 221, 88 275, 180 316)"));
    lines.add( Utils.toGeometry("LINESTRING (185 221, 292 281, 180 316)"));
    lines.add( Utils.toGeometry("LINESTRING (189 98, 83 187, 185 221)"));
    lines.add( Utils.toGeometry("LINESTRING (189 98, 325 168, 185 221)"));

    System.out.println("Lines:");
    for(Geometry g : lines) {
      System.out.println(" " + g);
      gv.add(g);
    }
    Utils.waitEnter();

    Polygonizer polygonizer = new Polygonizer();
    polygonizer.add(lines);
       /* two polygons will be formed, with two lines not being used */

    Collection polys = polygonizer.getPolygons();
    List<Geometry> geoms = new ArrayList<>();
    for (Object obj : polys)
      geoms.add((Geometry)obj);

    System.out.println("\nNo. of Polygons formed: " + geoms.size());
    for (Geometry geom : geoms) {
      System.out.println(" " + Utils.simplify(geom));
      gv.add(geom);
    }
  } /* main */


} // end of Polygonize class
