18

We can create a LineString using coordinates list like this:

     Geometry g1 = new GeometryFactory().createLineString(coordinates);

How can we create a polygon using coordinates list?

Thanks in advance.

Piscean
  • 3,069
  • 12
  • 47
  • 96

2 Answers2

41

The accepted answer might have still been valid (still awkward) in 2012 but nowadays you should really do it simply like this:

// Create a GeometryFactory if you don't have one already
GeometryFactory geometryFactory = new GeometryFactory();

// Simply pass an array of Coordinate or a CoordinateSequence to its method
Polygon polygonFromCoordinates = geometryFactory.createPolygon(coordinates);
bugmenot123
  • 1,069
  • 1
  • 18
  • 33
  • But it's create polygon with 3D.How to force to 2D? – Mr Lou May 04 '15 at 03:14
  • 2
    JTS is 2D. Coordinate objects have a third field but it is always NaN. Coordinate is not a Geometry in JTS. Point would be and it only has x and y. – bugmenot123 May 04 '15 at 16:29
  • 2
    Yes, bugmenot123 is right, with the current version of JTS you don't need to create a linearRing to create a polygon, a simple createPolygon is enough. Just keep in mind that the coordinates must form a closed ring (the first and the last point are the same) or you will get an exception. – Marko Letic Aug 25 '16 at 14:21
12

Use these line of codes:

 GeometryFactory fact = new GeometryFactory();
 LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
 Polygon poly = new Polygon(linear, null, fact);

I hope it will help :)

Piscean
  • 3,069
  • 12
  • 47
  • 96
  • 2
    If you want to set an especific SRID, you must create a GeometryFactory in this way: GeometryFactory fac = new GeometryFactory(new PrecisionModel(), _srid_);, replacing _srid_ with your desired SRID. – joninx Jan 22 '16 at 11:40