I need to create a GeoJSON stream, which contains data about roads. The roads are like polygons, except they are open (the start and end points are different).
I tried to use the following code to achieve that goal:
protected void addPolyLine(final double[] coords,
final GeometryBuilder builder,
final SimpleFeatureBuilder fbuilder,
final List<SimpleFeature> features,
final String id) {
final double[] modcoords = new double[coords.length+2];
for (int i=0; i < coords.length; i++) {
modcoords[i] = coords[i];
}
modcoords[modcoords.length-2] = coords[0];
modcoords[modcoords.length-1] = coords[1];
final double[] holeStart = new double[] {coords[0], coords[1],
coords[coords.length-2], coords[coords.length - 1]};
final LinearRing shell = builder.linearRing(modcoords);
final LinearRing hole = builder.linearRing(holeStart);
final Polygon polygon = builder.polygon(shell, hole);
fbuilder.add(polygon);
final SimpleFeature feature = fbuilder.buildFeature(id);
features.add(feature);
}
It doesn't work - I get the error
java.lang.IllegalArgumentException: Invalid number of points in LinearRing (found 3 - must be 0 or >= 4)
at com.vividsolutions.jts.geom.LinearRing.validateConstruction(LinearRing.java:114)
at com.vividsolutions.jts.geom.LinearRing.<init>(LinearRing.java:106)
at com.vividsolutions.jts.geom.GeometryFactory.createLinearRing(GeometryFactory.java:341)
at org.geotools.geometry.jts.GeometryBuilder.linearRing(GeometryBuilder.java:199)
When I use builder.lineString(coords)
, the resulting GeoJSON contains no coordinates as it should.
How can I create a polyline (a line, which connects several point and is not closed) using GeoTools 12-RC1?
Update 1 (05.07.2015 21:22 MSK): This is how I define feature types for points, polygons and lines. Points and polygons work fine, lines don't.
private final static SimpleFeatureType POINT =
createType("Test", "Location:Point");
private final static SimpleFeatureType POLYGON =
createType("Test2", "Location:Polygon");
private final BuildingsReader buildingsReader =
new DefaultBuildingsReader();
private final static SimpleFeatureType LINE =
createType("Test3", "Line");
private static SimpleFeatureType createType(final String x1, final String x2) {
try
{
return DataUtilities.createType(x1, x2);
}
catch (final SchemaException exception) {
exception.printStackTrace();
}
return null;
}
You need to do something with createLineString like:
line=builder.createLineString(Arrays.asList(coords));
fbuilder.add(line);
final SimpleFeature feature = fbuilder.buildFeature(id);
features.add(feature);
You will need to modify your feature type to expect a line instead of a polygon.