Java Code Examples for org.locationtech.jts.geom.LineString

The following examples show how to use org.locationtech.jts.geom.LineString. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: constellation   Source File: StyleGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static Style createStyle(final SimpleFeatureCollection features) {
    if (features.size() == 0) {
        LOGGER.warning("No features available to generate style");
        return null;
    }

    final Class<?> geometryType = features.getSchema().getGeometryDescriptor().getType().getBinding();
    if (Polygon.class.isAssignableFrom(geometryType)
            || MultiPolygon.class.isAssignableFrom(geometryType)) {
        return createPolygonStyle();
    } else if (LineString.class.isAssignableFrom(geometryType)) {
        return createLineStyle();
    } else if (Point.class.isAssignableFrom(geometryType)) {
        return createPointStyle();
    } else {
        LOGGER.log(Level.WARNING, "Style cannot be generated from type: {0}", geometryType);
        return null;
    }
}
 
Example 2
Source Project: searoute   Source File: MarnetBuilding.java    License: European Union Public License 1.2 6 votes vote down vote up
/**
 * Build a maritime network from a list of linear features representing maritime lines
 * for specified resolutions
 * 
 * @param resDegs The target resolution (in geographical coordinates).
 * @param fs Feature collections.
 * @return
 */
public static Collection<LineString>[] makeFromLinearFeatures(double[] resDegs, Collection<Feature>... fs) {
	Collection<LineString>[] out = new ArrayList[resDegs.length];
	for(int i=0; i<resDegs.length; i++) {
		LOGGER.info("Build maritime network for resolution " + resDegs[i]);
		out[i] = makeFromLinearFeatures(resDegs[i], fs);
	}
	return out;
}
 
Example 3
@Test
public void testObservation() {
    assertThat(observation, is(notNullValue()));
    final String type = observation.getObservationConstellation().getObservationType();
    assertThat(type, is(equalTo(OmConstants.OBS_TYPE_GEOMETRY_OBSERVATION)));
    final ObservationValue<?> value = observation.getValue();
    assertThat(value, is(instanceOf(SingleObservationValue.class)));
    assertThat(value.getPhenomenonTime(), is(instanceOf(TimeInstant.class)));
    TimeInstant pt = (TimeInstant) value.getPhenomenonTime();
    assertThat(pt.getValue(), is(equalTo(phenomenonTime)));
    assertThat(value.getValue(), is(instanceOf(GeometryValue.class)));
    GeometryValue v = (GeometryValue) value.getValue();
    assertThat(v.getUnit(), is(nullValue()));
    Geometry g = v.getValue();
    assertThat(g, is(instanceOf(LineString.class)));
    assertThat(g.getSRID(), is(2000));
    assertThat(g.getNumPoints(), is(2));
    assertThat(g.getCoordinates()[0], is(equalTo(new Coordinate(52, 7))));
    assertThat(g.getCoordinates()[1], is(equalTo(new Coordinate(51, 7))));
}
 
Example 4
Source Project: snap-desktop   Source File: ShapeConverter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object parse(String text) throws ConversionException {
    try {
        Geometry geometry = new WKTReader(geometryFactory).read(text);
        if (geometry instanceof LineString) {
            LineString lineString = (LineString) geometry;
            // todo
            return null;
        } else if (geometry instanceof Polygon) {
            Polygon polygon = (Polygon) geometry;
            // todo
            return null;
        } else {
            throw new ConversionException("Failed to parse shape geometry WKT.");
        }
    } catch (ParseException e) {
        throw new ConversionException("Failed to parse shape geometry WKT.", e);
    }
}
 
Example 5
Source Project: sldeditor   Source File: ExtractAttributes.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * (non-Javadoc)
 *
 * @see
 *     org.geotools.styling.visitor.DuplicatingStyleVisitor#visit(org.geotools.styling.LineSymbolizer)
 */
@Override
public void visit(LineSymbolizer line) {
    LineSymbolizer copy = sf.getDefaultLineSymbolizer();

    copy.setGeometry(copy(LineString.class, line.getGeometry()));

    copy.setUnitOfMeasure(line.getUnitOfMeasure());
    copy.setStroke(copy(line.getStroke()));
    copy.getOptions().putAll(line.getOptions());
    copy.setPerpendicularOffset(line.getPerpendicularOffset());

    if (STRICT && !copy.equals(line)) {
        throw new IllegalStateException(
                "Was unable to duplicate provided LineSymbolizer:" + line);
    }
    pages.push(copy);
}
 
Example 6
private Geometry getGeometryFromShape(Shape shape) {
    AwtGeomToJtsGeomConverter converter = new AwtGeomToJtsGeomConverter();
    Geometry geometry;
    // May need to handle more cases here in the future!  (nf)
    if (Polygon.class.isAssignableFrom(geometryType)) {
        geometry = converter.createPolygon(shape);
    } else if (MultiPolygon.class.isAssignableFrom(geometryType)) {
        geometry = converter.createMultiPolygon(shape);
    } else if (LinearRing.class.isAssignableFrom(geometryType)) {
        geometry = converter.createLinearRingList(shape).get(0);
    } else if (LineString.class.isAssignableFrom(geometryType)) {
        geometry = converter.createLineStringList(shape).get(0);
    } else {
        geometry = converter.createMultiLineString(shape);
    }
    return geometry;
}
 
Example 7
Source Project: sldeditor   Source File: FilterManagerTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/** Sets the up class. */
@BeforeAll
public static void setUpClass() {
    typeMap.put(Number.class, FieldConfigDouble.class);
    typeMap.put(Double.class, FieldConfigDouble.class);
    typeMap.put(Float.class, FieldConfigDouble.class);
    typeMap.put(Integer.class, FieldConfigInteger.class);
    typeMap.put(Long.class, FieldConfigInteger.class);
    typeMap.put(String.class, FieldConfigString.class);
    typeMap.put(Object.class, FieldConfigString.class);
    typeMap.put(Boolean.class, FieldConfigBoolean.class);
    typeMap.put(Geometry.class, FieldConfigGeometry.class);
    typeMap.put(org.opengis.geometry.Geometry.class, FieldConfigGeometry.class);
    typeMap.put(LineString.class, FieldConfigGeometry.class);
    typeMap.put(Date.class, FieldConfigDate.class);
    typeMap.put(Class.class, FieldConfigString.class);
    typeMap.put(Color.class, FieldConfigColour.class);
    typeMap.put(Classifier.class, FieldConfigString.class);
    typeMap.put(Unit.class, FieldConfigMapUnits.class);
    typeMap.put(Comparable.class, FieldConfigString.class);
}
 
Example 8
Source Project: snap-desktop   Source File: ShapefileLoader.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Style[] createStyle(File shapeFile, FeatureType schema) {
    final Style[] styles = SLDUtils.loadSLD(shapeFile);
    if (styles != null && styles.length > 0) {
        return styles;
    }
    Class<?> type = schema.getGeometryDescriptor().getType().getBinding();
    if (type.isAssignableFrom(Polygon.class)
            || type.isAssignableFrom(MultiPolygon.class)) {
        return new Style[]{createPolygonStyle()};
    } else if (type.isAssignableFrom(LineString.class)
            || type.isAssignableFrom(MultiLineString.class)) {
        return new Style[]{createLineStyle()};
    } else {
        return new Style[]{createPointStyle()};
    }
}
 
Example 9
Source Project: geopaparazzi   Source File: ShapeWriter.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link Shape} representing a {@link Geometry},
 * according to the specified PointTransformation
 * and PointShapeFactory (if relevant).
 * <p>
 * Note that Shapes do not
 * preserve information fragment_about which elements in heterogeneous collections
 * are 1D and which are 2D.
 * For example, a GeometryCollection containing a ring and a
 * disk will render as two disks if Graphics.fill is used,
 * or as two rings if Graphics.draw is used.
 * To avoid this issue use separate shapes for the components.
 *
 * @param geometry the geometry to convert
 * @return a Shape representing the geometry
 */
public DrawableShape toShape(Geometry geometry) {
    if (geometry.isEmpty())
        return new PathShape(new Path());
    else if (geometry instanceof Polygon)
        return toShape((Polygon) geometry);
    else if (geometry instanceof MultiPolygon)
        return toShape((MultiPolygon) geometry);
    else if (geometry instanceof LineString)
        return toShape((LineString) geometry);
    else if (geometry instanceof MultiLineString)
        return toShape((MultiLineString) geometry);
    else if (geometry instanceof Point)
        return toShape((Point) geometry);
    else if (geometry instanceof MultiPoint)
        return toShape((MultiPoint) geometry);
    else if (geometry instanceof GeometryCollection)
        return toShape((GeometryCollection) geometry);

    throw new IllegalArgumentException("Unrecognized Geometry class: " + geometry.getClass());
}
 
Example 10
private void createPoints( CoordinateReferenceSystem crs, GeometryFactory gf, List<LineString> verticals,
        List<LineString> horizontals ) {
    outMap = new DefaultFeatureCollection();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(POINT);
    b.setCRS(crs);
    b.add("the_geom", Point.class);
    b.add("id", Long.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder fbuilder = new SimpleFeatureBuilder(type);

    Geometry gVer = gf.createMultiLineString(verticals.toArray(new LineString[0]));
    Geometry gHor = gf.createMultiLineString(horizontals.toArray(new LineString[0]));

    Geometry intersection = gHor.intersection(gVer);

    long index = 0;
    int numGeometries = intersection.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometry = intersection.getGeometryN(i);
        Object[] values = new Object[]{geometry, index++};
        fbuilder.addAll(values);
        SimpleFeature feature = fbuilder.buildFeature(null);
        ((DefaultFeatureCollection) outMap).add(feature);
    }
}
 
Example 11
/**
 * check the width of the section against the given thresholds
 * and create the section linestring
 */
private void assign( LinkedHashMap<SimpleFeature, double[]> validPointsMap,
        LinkedHashMap<SimpleFeature, String> problemPointsMap, ConcurrentLinkedQueue<Object[]> validPointsLineList,
        SimpleFeature netFeature, Object linkId, Object pfaf, double progressive, double[] attributes,
        Coordinate nearestOnChannelCoordinate, Coordinate coordinate ) {
    double width = coordinate.distance(nearestOnChannelCoordinate);
    if (width > pMaxNetworkWidth) {
        problemPointsMap.put(netFeature, FOUND_INVALID_NETWORK_WIDTH_LARGE);
    } else if (width < pMinNetworkWidth) {
        problemPointsMap.put(netFeature, FOUND_INVALID_NETWORK_WIDTH_SMALL);
    } else {
        attributes[0] = width;
        attributes[1] = WIDTH_FROM_CHANNELEDIT;

        LineString widthLine = gf.createLineString(new Coordinate[]{coordinate, nearestOnChannelCoordinate});
        Object[] newLineAttr = {widthLine, pfaf, linkId, linkId, progressive};
        validPointsLineList.add(newLineAttr);
        validPointsMap.put(netFeature, attributes);
    }
}
 
Example 12
/**
 * Builds a line feature from a dwg polyline 3D.
 * 
 * TODO handle these as contourlines
 * 
 */
public SimpleFeature convertDwgPolyline3D( String typeName, String layerName,
        DwgPolyline3D polyline3d, int id ) {
    double[][] ptos = polyline3d.getPts();
    CoordinateList coordList = new CoordinateList();
    if (ptos != null) {
        for( int j = 0; j < ptos.length; j++ ) {
            Coordinate coord = new Coordinate(ptos[j][0], ptos[j][1], ptos[j][2]);
            coordList.add(coord);
        }

        SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
        b.setName(typeName);
        b.setCRS(crs);
        b.add(THE_GEOM, LineString.class);
        b.add(LAYER, String.class);
        SimpleFeatureType type = b.buildFeatureType();
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Geometry lineString = gF.createLineString(coordList.toCoordinateArray());
        Object[] values = new Object[]{lineString, layerName};
        builder.addAll(values);
        return builder.buildFeature(typeName + "." + id);
    }
    return null;
}
 
Example 13
/**
 * Builds a line feature from a dwg polyline 2D.
 * 
 */
public SimpleFeature convertDwgPolyline2D( String typeName, String layerName,
        DwgPolyline2D polyline2d, int id ) {
    Point2D[] ptos = polyline2d.getPts();
    CoordinateList coordList = new CoordinateList();
    if (ptos != null) {
        for( int j = 0; j < ptos.length; j++ ) {
            Coordinate coord = new Coordinate(ptos[j].getX(), ptos[j].getY(), 0.0);
            coordList.add(coord);
        }

        SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
        b.setName(typeName);
        b.setCRS(crs);
        b.add(THE_GEOM, LineString.class);
        b.add(LAYER, String.class);
        SimpleFeatureType type = b.buildFeatureType();
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Geometry lineString = gF.createLineString(coordList.toCoordinateArray());
        Object[] values = new Object[]{lineString, layerName};
        builder.addAll(values);
        return builder.buildFeature(typeName + "." + id);
    }
    return null;
}
 
Example 14
/**
 * Builds a line feature from a dwg line.
 * 
 */
public SimpleFeature convertDwgLine( String typeName, String layerName, DwgLine line, int id ) {
    double[] p1 = line.getP1();
    double[] p2 = line.getP2();
    Point2D[] ptos = new Point2D[]{new Point2D.Double(p1[0], p1[1]),
            new Point2D.Double(p2[0], p2[1])};
    CoordinateList coordList = new CoordinateList();
    for( int j = 0; j < ptos.length; j++ ) {
        Coordinate coord = new Coordinate(ptos[j].getX(), ptos[j].getY(), 0.0);
        coordList.add(coord);
    }

    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(typeName);
    b.setCRS(crs);
    b.add(THE_GEOM, LineString.class);
    b.add(LAYER, String.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    Geometry lineString = gF.createLineString(coordList.toCoordinateArray());
    Object[] values = new Object[]{lineString, layerName};
    builder.addAll(values);
    return builder.buildFeature(typeName + "." + id);
}
 
Example 15
Source Project: hortonmachine   Source File: TestProfile.java    License: GNU General Public License v3.0 6 votes vote down vote up
private SimpleFeatureCollection doCollection() {
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("typename");
    b.setCRS(crs);
    b.add("the_geom", LineString.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);

    Coordinate one = new Coordinate(westNorth.x + ep.getXres() / 2, centerCoord.y + ep.getYres() / 2);
    Coordinate two = new Coordinate(eastSouth.x - ep.getXres() / 2, centerCoord.y + ep.getYres() / 2);

    LineString lineString = GeometryUtilities.gf().createLineString(new Coordinate[]{one, two});
    Object[] values = new Object[]{lineString};
    builder.addAll(values);
    SimpleFeature feature = builder.buildFeature(null);
    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    newCollection.add(feature);
    return newCollection;
}
 
Example 16
public void testLineMerger() throws Exception {
    String l1 = "LINESTRING (0 300, 200 300, 200 200)";
    String l2 = "LINESTRING (200 0, 200 200)";
    String l3 = "LINESTRING (50 100, 250 100, 300 100)";
    String l4 = "LINESTRING (300 100, 300 0)";
    String l5 = "LINESTRING (50 100, 50 0, 200 0)";

    WKTReader r = new WKTReader();
    LineString g1 = (LineString) r.read(l1);
    LineString g2 = (LineString) r.read(l2);
    LineString g3 = (LineString) r.read(l3);
    LineString g4 = (LineString) r.read(l4);
    LineString g5 = (LineString) r.read(l5);

    List<LineString> mergeLinestrings = GeometryUtilities.mergeLinestrings(Arrays.asList(g1, g2, g3, g4));
    assertEquals(2, mergeLinestrings.size());
    mergeLinestrings = GeometryUtilities.mergeLinestrings(Arrays.asList(g1, g2, g3, g4, g5));
    assertEquals(1, mergeLinestrings.size());

}
 
Example 17
Source Project: hortonmachine   Source File: CommonQueries.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the GeodesicLength between to points.
 * 
 * @param connection the database connection.
 * @param p1 the first point.
 * @param p2 the second point.
 * @param srid the srid. If <0, 4326 will be used. This needs to be a geographic prj.
 * @return the distance.
 * @throws Exception
 */
public static double getDistanceBetween( IHMConnection connection, Coordinate p1, Coordinate p2, int srid ) throws Exception {
    if (srid < 0) {
        srid = 4326;
    }
    GeometryFactory gf = new GeometryFactory();
    LineString lineString = gf.createLineString(new Coordinate[]{p1, p2});
    String sql = "select GeodesicLength(LineFromText(\"" + lineString.toText() + "\"," + srid + "));";
    try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(sql);) {
        if (rs.next()) {
            double length = rs.getDouble(1);
            return length;
        }
        throw new RuntimeException("Could not calculate distance.");
    }

}
 
Example 18
Source Project: presto   Source File: JtsGeometrySerde.java    License: Apache License 2.0 5 votes vote down vote up
private static Geometry readPolyline(SliceInput input, boolean multitype)
{
    skipEsriType(input);
    skipEnvelope(input);
    int partCount = input.readInt();
    if (partCount == 0) {
        if (multitype) {
            return GEOMETRY_FACTORY.createMultiLineString();
        }
        return GEOMETRY_FACTORY.createLineString();
    }

    int pointCount = input.readInt();
    int[] startIndexes = new int[partCount];
    for (int i = 0; i < partCount; i++) {
        startIndexes[i] = input.readInt();
    }

    int[] partLengths = new int[partCount];
    if (partCount > 1) {
        partLengths[0] = startIndexes[1];
        for (int i = 1; i < partCount - 1; i++) {
            partLengths[i] = startIndexes[i + 1] - startIndexes[i];
        }
    }
    partLengths[partCount - 1] = pointCount - startIndexes[partCount - 1];

    LineString[] lineStrings = new LineString[partCount];

    for (int i = 0; i < partCount; i++) {
        lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, partLengths[i]));
    }

    if (multitype) {
        return GEOMETRY_FACTORY.createMultiLineString(lineStrings);
    }
    verify(lineStrings.length == 1);
    return lineStrings[0];
}
 
Example 19
/**
 * Constructor
 *
 * @param geometry Geometry
 */
public PolylineShape(Geometry geometry) {
    this();
    Coordinate[] cs = geometry.getCoordinates();
    List<PointD> points = new ArrayList();
    for (Coordinate c : cs) {
        points.add(new PointD(c.x, c.y));
    }
    switch (geometry.getGeometryType()) {
        case "MultiLineString":
            this._points = points;
            List<PointD> pp;
            int n = geometry.getNumGeometries();
            _numParts = n;
            List<Integer> partlist = new ArrayList<>();
            int idx = 0;
            for (int i = 0; i < n; i++) {
                LineString poly = (LineString) geometry.getGeometryN(i);
                partlist.add(idx);
                Polyline polyline = new Polyline();
                pp = new ArrayList<>();
                for (int j = idx; j < idx + poly.getNumPoints(); j++) {
                    pp.add(points.get(j));
                }
                polyline.setPointList(pp);
                idx += poly.getNumPoints();
                ((List<Polyline>) this._polylines).add(polyline);
            }
            parts = new int[n];
            for (int i = 0; i < parts.length; i++) {
                parts[i] = partlist.get(i);
            }
            this.setExtent(MIMath.getPointsExtent(_points));
            break;
        default:
            this.setPoints(points);
            break;
    }
}
 
Example 20
Source Project: searoute   Source File: MarnetBuilding.java    License: European Union Public License 1.2 5 votes vote down vote up
/**
 * Build a maritime network from a list of linear features representing maritime lines.
 * 
 * @param resDeg The target resolution (in geographical coordinates).
 * @param fs Feature collections.
 * @return
 */
public static Collection<LineString> makeFromLinearFeatures(double resDeg, Collection<Feature>... fs) {
	//load input lines
	Collection<LineString> lines = new HashSet<LineString>();

	//data sources preparation
	for(Collection<Feature> fs_ : fs) {
		LOGGER.debug(" preparing " + fs_.size());
		Collection ls = FeatureUtil.featuresToGeometries(fs_);
		ls = prepare(ls, resDeg);
		lines.addAll(ls);
	}
	return make(resDeg, lines);
}
 
Example 21
private void addLine( Geometry geometry, BasicShapeAttributes shapeAttributes, boolean convert ) {
        if (geometry == null) {
            return;
        }
        Coordinate[] coordinates = geometry.getCoordinates();
        if (coordinates.length < 2)
            return;

        int numGeometries = geometry.getNumGeometries();
        for( int i = 0; i < numGeometries; i++ ) {
            Geometry geometryN = geometry.getGeometryN(i);
            if (geometryN instanceof LineString) {
                LineString line = (LineString) geometryN;
                Coordinate[] lineCoords = line.getCoordinates();
                int numVertices = lineCoords.length;
                List<Position> verticesList = new ArrayList<>(numVertices);
                for( int j = 0; j < numVertices; j++ ) {
                    Coordinate c = lineCoords[j];
                    if (convert) {
                        c = MercatorUtils.convert3857To4326(c);
                    }
                    bounds.expandToInclude(c);
                    verticesList.add(Position.fromDegrees(c.y, c.x));
                }
                FeatureLine path = new FeatureLine(verticesList, null);
//                path.setFeature(lineFeature);
                path.setAltitudeMode(mElevationMode);
                path.setAttributes(shapeAttributes);
                path.setHighlightAttributes(highlightAttrs);

                addRenderable(path);
            }
        }
    }
 
Example 22
Source Project: searoute   Source File: MarnetBuilding.java    License: European Union Public License 1.2 5 votes vote down vote up
private static Collection<LineString> prepare(Collection<LineString> lines, double res) {
	lines = GraphSimplify.planifyLines(lines);						LOGGER.debug(lines.size() + " planifyLines");
	lines = GraphSimplify.lineMerge(lines);							LOGGER.debug(lines.size() + " lineMerge");
	lines = DouglasPeuckerRamerFilter.get(lines, res);						LOGGER.debug(lines.size() + " filterGeom");
	lines = GraphSimplify.removeSimilarDuplicateEdges(lines, res);	LOGGER.debug(lines.size() + " removeSimilarDuplicateEdges");
	lines = GraphSimplify.collapseTooShortEdgesAndPlanifyLines(lines, res, true, true);				LOGGER.debug(lines.size() + " dtsePlanifyLines");
	lines = GraphSimplify.resPlanifyLines(lines, res*0.01, false);			LOGGER.debug(lines.size() + " resPlanifyLines");
	return lines;
}
 
Example 23
Source Project: geowave   Source File: GeometryHullToolTest.java    License: Apache License 2.0 5 votes vote down vote up
private Geometry getHull(
    final LineString str,
    final String name,
    final boolean save,
    final boolean parkandOh) {

  final List<Point> points = CurvedDensityDataGeneratorTool.generatePoints(str, 0.4, 1000);

  final GeometryHullTool cg = new GeometryHullTool();
  cg.setDistanceFnForCoordinate(new CoordinateCircleDistanceFn());

  final Coordinate[] coordinates = new Coordinate[points.size()];
  int i = 0;
  for (final Point point : points) {
    coordinates[i++] = point.getCoordinate();
  }

  final ConvexHull convexHull = new ConvexHull(coordinates, factory);

  final Geometry concaveHull =
      parkandOh
          ? cg.concaveHullParkOhMethod(convexHull.getConvexHull(), Arrays.asList(coordinates))
          : cg.concaveHull(convexHull.getConvexHull(), Arrays.asList(coordinates));
  if (save || !concaveHull.isSimple()) {
    writeToShapeFile("setx_" + name, points.toArray(new Geometry[points.size()]));
    writeToShapeFile("chullx_" + name, concaveHull);
    writeToShapeFile("hullx_" + name, convexHull.getConvexHull());
  }

  // final Geometry concaveHull1 = cg.concaveHull1(
  // convexHull.getConvexHull(),
  // Arrays.asList(coordinates));
  // if (save || !concaveHull1.isSimple()) {
  // writeToShapeFile(
  // "chull_" + name,
  // concaveHull1);
  // }

  return concaveHull;
}
 
Example 24
Source Project: sis   Source File: GeometryTransform.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Transforms the given geometry. This method delegates to one of the {@code transform(…)} methods
 * based on the type of the given geometry.
 *
 * @param  geom  the geometry to transform.
 * @return the transformed geometry.
 * @throws TransformException if an error occurred while transforming the geometry.
 */
public Geometry transform(final Geometry geom) throws TransformException {
    if (geom instanceof Point)              return transform((Point)              geom);
    if (geom instanceof MultiPoint)         return transform((MultiPoint)         geom);
    if (geom instanceof LinearRing)         return transform((LinearRing)         geom);    // Must be tested before LineString.
    if (geom instanceof LineString)         return transform((LineString)         geom);
    if (geom instanceof MultiLineString)    return transform((MultiLineString)    geom);
    if (geom instanceof Polygon)            return transform((Polygon)            geom);
    if (geom instanceof MultiPolygon)       return transform((MultiPolygon)       geom);
    if (geom instanceof GeometryCollection) return transform((GeometryCollection) geom);
    throw new IllegalArgumentException(Errors.format(Errors.Keys.UnsupportedType_1, Classes.getClass(geom)));
}
 
Example 25
Source Project: arctic-sea   Source File: TrajectoryObservation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create geometry for featureOfInterest from
 * {@link TimeLocationValueTriple}s
 *
 * @param values
 *            The {@link TimeLocationValueTriple}s to check for
 *            featureOfInterest
 */
private void checkForFeature(List<TimeLocationValueTriple> values) {
    AbstractFeature featureOfInterest = getObservationConstellation().getFeatureOfInterest();
    if (featureOfInterest instanceof AbstractSamplingFeature) {
        AbstractSamplingFeature sf = (AbstractSamplingFeature) featureOfInterest;
        Coordinate[] coords = getCoordinates(values);
        int srid = 0;
        if (sf.isSetGeometry()) {
            srid = sf.getGeometry().getSRID();
            coords = (Coordinate[]) ArrayUtils.addAll(sf.getGeometry().getCoordinates(), coords);
        } else {
            TimeLocationValueTriple next = values.iterator().next();
            if (next.isSetLocation()) {
                srid = next.getLocation().getSRID();
            }
        }
        try {
            if (coords.length == 1) {
                Point point = new GeometryFactory().createPoint(coords[0]);
                point.setSRID(srid);
                sf.setGeometry(point);
            } else if (coords.length > 1) {
                LineString lineString = new GeometryFactory().createLineString(coords);
                lineString.setSRID(srid);
                sf.setGeometry(lineString);
            }
        } catch (InvalidSridException e) {
            // TODO
        }
    }
}
 
Example 26
Source Project: arctic-sea   Source File: ProfileObservation.java    License: Apache License 2.0 5 votes vote down vote up
private void setFeatureGeometry(List<Coordinate> coordinates, int srid) {
    AbstractFeature featureOfInterest = getObservationConstellation().getFeatureOfInterest();
    if (featureOfInterest instanceof AbstractSamplingFeature) {
        AbstractSamplingFeature sf = (AbstractSamplingFeature) featureOfInterest;
        Coordinate[] coords = coordinates.toArray(new Coordinate[0]);
        try {
            LineString lineString = new GeometryFactory().createLineString(coords);
            lineString.setSRID(srid);
            sf.setGeometry(lineString);
            sf.setFeatureType(SfConstants.SAMPLING_FEAT_TYPE_SF_SAMPLING_CURVE);
        } catch (InvalidSridException e) {
            // TODO
        }
    }
}
 
Example 27
Source Project: arctic-sea   Source File: JTSHelper.java    License: Apache License 2.0 5 votes vote down vote up
public Geometry convertSequence(Geometry geometry) {
    if (geometry instanceof Point) {
        return createPoint(((Point) geometry).getCoordinateSequence());
    } else if (geometry instanceof LinearRing) {
        return createLinearRing(((LinearRing) geometry).getCoordinates());
    } else if (geometry instanceof LineString) {
        return createLineString(((LineString) geometry).getCoordinates());
    } else if (geometry instanceof Polygon) {
        LinearRing[] linearRings = new LinearRing[((Polygon) geometry).getNumInteriorRing()];
        for (int i = 0; i < ((Polygon) geometry).getNumInteriorRing(); i++) {
            linearRings[i] = (LinearRing) convertSequence(((Polygon) geometry).getInteriorRingN(i));
        }
        return createPolygon((LinearRing) convertSequence(((Polygon) geometry).getExteriorRing()),
                linearRings);
    } else if (geometry instanceof MultiPoint) {
        return createMultiPointFromCoords(((MultiPoint) geometry).getCoordinates());
    } else if (geometry instanceof MultiLineString) {
        LineString[] lineStrings = new LineString[((MultiLineString) geometry).getNumGeometries()];
        for (int i = 0; i < ((MultiLineString) geometry).getNumGeometries(); i++) {
            lineStrings[i] = (LineString) convertSequence(((MultiLineString) geometry).getGeometryN(i));
        }
        return createMultiLineString(lineStrings);
    } else if (geometry instanceof MultiPolygon) {
        Polygon[] polygons = new Polygon[((MultiPolygon) geometry).getNumGeometries()];
        for (int i = 0; i < ((MultiPolygon) geometry).getNumGeometries(); i++) {
            polygons[i] = (Polygon) convertSequence(((MultiPolygon) geometry).getGeometryN(i));
        }
        return createMultiPolygon(polygons);
    } else if (geometry instanceof GeometryCollection) {
        Geometry[] geometries = new Geometry[((GeometryCollection) geometry).getNumGeometries()];
        for (int i = 0; i < ((GeometryCollection) geometry).getNumGeometries(); i++) {
            geometries[i] = convertSequence(((GeometryCollection) geometry).getGeometryN(i));
        }
        return createGeometryCollection(geometries);
    }
    return geometry;
}
 
Example 28
Source Project: sis   Source File: JTS.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the given list of line string as a single geometry.
 */
private Geometry toGeometry(final List<LineString> lines) {
    final int s = lines.size();
    switch (s) {
        case 0:  return factory.createLinearRing((Coordinate[]) null);      // Creates an empty linear ring.
        case 1:  return lines.get(0);
        default: return factory.createMultiLineString(lines.toArray(new LineString[s]));
    }
}
 
Example 29
Source Project: arctic-sea   Source File: GeoJSONDecoder.java    License: Apache License 2.0 5 votes vote down vote up
protected MultiLineString decodeMultiLineString(JsonNode node, GeometryFactory fac)
        throws GeoJSONDecodingException {
    JsonNode coordinates = requireCoordinates(node);
    LineString[] lineStrings = new LineString[coordinates.size()];
    for (int i = 0; i < coordinates.size(); ++i) {
        JsonNode coords = coordinates.get(i);
        lineStrings[i] = fac.createLineString(decodeCoordinates(coords));
    }
    return fac.createMultiLineString(lineStrings);
}
 
Example 30
private SimpleFeatureType createPathType() {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("debrispaths");
    b.setCRS(inFlow.getCoordinateReferenceSystem());
    b.add("the_geom", LineString.class);
    b.add("ID", Integer.class);
    SimpleFeatureType type = b.buildFeatureType();
    return type;
}