# JTS: generate a polygon geometry from line geomtry

I have a line and I wish to convert it to a polygon.
The point is this line is NOT a ring it's an straight Line. And I want to use an specific width to extend line horizontally and create a polygon.

Using JTS. is it possible? How can I make it happen?

• It depends, is your line in lat/lon? Does the width have to be horizontal? – Ian Turton Jul 29 '18 at 18:25
• No! Line is in 3857 projection points and yes width is horizontal – alizeyn Jul 29 '18 at 18:28
• Then it is simple maths – Ian Turton Jul 29 '18 at 18:28

Since you want a simple horizontal offset this is quite easy, you need to reverse the order of the points and then add each one in turn with the x offset applied and create a polygon from the linestring.

``````package spike;

import java.util.ArrayList;
import java.util.Arrays;

import org.apache.commons.lang.ArrayUtils;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Polygon;

public class LineToPoly {
static GeometryFactory gf = new GeometryFactory();

public static void main(String[] args) {
Coordinate[] points = {new Coordinate(10000,10000),new Coordinate(12300,40000),new Coordinate(16800,50000),new Coordinate(12354,60000)};
LineString line = gf.createLineString(points );

double offset = 1000; //1km
System.out.println(line);
Polygon p = generatePoly(line,offset);
System.out.println(p);
}

private static Polygon generatePoly(LineString line, double offset) {

Coordinate[] points = line.getCoordinates();

ArrayList<Coordinate> soln = new ArrayList<>();
//store initial points
// reverse the list
ArrayUtils.reverse(points);
// for each point move offset metres right
for (Coordinate c:points) {
}
// close the polygon
``````LINESTRING (10000 10000, 12300 40000, 16800 50000, 12354 60000)