Search code examples
javagisgeotoolsjts

JTS: How to convert polygon into MultiLineString


I have polygon shape and I want to convert it to MultiLineString. Note that usually the direction is different: From points, coords, lines etc. using GeometryFactory build polygon. I started to thinking about GeometryTransformer but it's hard to understand the documentation there... So I have this:

import com.vividsolutions.jts.geom.*;
...
GeometryFactory gFactory = new GeometryFactory();
GeometryTransformer gTransform = new GeometryTransformer();
Polygon polygon = gFactory.createPolygon(someLinearRing, null);
MultiLineString mlString = polygon.TODO?

How to continue in the TODO?


Solution

  • The method Polygon.getBoundary() computes the boundaries of the polygon. If the polygon has not holes (also only one boundary), a object of type LinearRing is returned. If the polygons has holes - also more than one boundary - a object of type MultiLineString is returned.

    Use the methode Polygon.getNumInteriorRing() to check if the polygon has holes and than build a multilinestring is necessary:

    GeometryFactory gFactory = new GeometryFactory();
    if (polygon.getNumInteriorRing() == 0){
      // polygon has not holes, so extract the exterior ring
      // and build a multilinestring
      return gFactory.createMultiLineString(polygon.getExteriorRing());
    }
    
    else{
      // Polygon has holes, also several boundaries. 
      // Simply run getBoundary(), it will return a multilinestring
      return polygon.getBoundary();
    }