1

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
1

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
    soln.addAll(Arrays.asList(points));
    // reverse the list
    ArrayUtils.reverse(points);
    // for each point move offset metres right 
    for (Coordinate c:points) {
      soln.add(new Coordinate(c.x+offset, c.y));
    }
    // close the polygon
    soln.add(soln.get(0));
    // create polygon
    Polygon poly = gf.createPolygon(soln.toArray(new Coordinate[] {}));
    return poly;
  }

}

This gives the following:

LINESTRING (10000 10000, 12300 40000, 16800 50000, 12354 60000)
POLYGON ((10000 10000, 12300 40000, 16800 50000, 12354 60000, 13354 60000, 17800 50000, 13300 40000, 11000 10000, 10000 10000))

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.