
// LinesMerge.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

/* Sew lines together using LineMerger.
   The merging is visible in GeomsViewer since separate lines
   are drawn in different colors, and the number of colors
   reduces. In this example, 13 lines become 5 (i.e. 13
   colors reduce to just 5).

   Usage:
    > compile LinesMerge.java
    > run LinesMerge

  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.linemerge.LineMerger;



public class LinesMerge
{

  public static void main(String[] args) throws Exception
  {
    GeomsViewer gv = Utils.view("Merged Lines");

    List<Geometry> lines = getData();
    System.out.println("No. of lines: " + lines.size());
    for (Geometry geom : lines) {
      System.out.println(" " + geom);
      gv.add(geom);
    }

    Utils.waitEnter();

    LineMerger lineMerger = new LineMerger();
    lineMerger.add(lines);
    Collection items = lineMerger.getMergedLineStrings();

    List<Geometry> mergedLines = new ArrayList<>();
    for (Object obj : items)
      mergedLines.add((Geometry)obj);

    gv.clear();
    System.out.println("No. of merged lines: " + mergedLines.size());
    for (Geometry geom : mergedLines) {
      System.out.println(" " + Utils.simplify(geom));
      gv.add(geom);
    }

    Utils.waitEnter();
    gv.close();
  } /* main */


  private static List<Geometry> getData()
  {
    List<Geometry> lines = new ArrayList<>();
    lines.add( Utils.toGeometry("LINESTRING (220 160, 240 150, 270 150, 290 170)"));
    lines.add( Utils.toGeometry("LINESTRING (60 210, 30 190, 30 160)"));
    lines.add( Utils.toGeometry("LINESTRING (70 430, 100 430, 120 420, 140 400)"));
    lines.add( Utils.toGeometry("LINESTRING (160 310, 160 280, 160 250, 170 230)"));
    lines.add( Utils.toGeometry("LINESTRING (170 230, 180 210, 200 180, 220 160)"));
    lines.add( Utils.toGeometry("LINESTRING (30 160, 40 150, 70 150)"));
    lines.add( Utils.toGeometry("LINESTRING (160 310, 200 330, 220 340, 240 360)"));
    lines.add( Utils.toGeometry("LINESTRING (140 400, 150 370, 160 340, 160 310)"));
    lines.add( Utils.toGeometry("LINESTRING (160 310, 130 300, 100 290, 70 270)"));
    lines.add( Utils.toGeometry("LINESTRING (240 360, 260 390, 260 410, 250 430)"));
    lines.add( Utils.toGeometry("LINESTRING (70 150, 100 180, 100 200)"));
    lines.add( Utils.toGeometry("LINESTRING (70 270, 60 260, 50 240, 50 220, 60 210)"));
    lines.add( Utils.toGeometry("LINESTRING (100 200, 90 210, 60 210)"));

    return lines;
  } /* getData */

}  // end of LinesMerge class
