org.locationtech.jts.geom.GeometryCollection Java Examples

The following examples show how to use org.locationtech.jts.geom.GeometryCollection. 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 File: GeoWaveFunctionsDescriptor.java    From datawave with Apache License 2.0 6 votes vote down vote up
protected static Geometry findIntersectedGeoms(Geometry srcGeom, List<Geometry> geometries) {
    List<Geometry> intersected = new ArrayList<>();
    
    // find all geometries which intersect with with srcGeom
    Iterator<Geometry> geomIter = geometries.iterator();
    while (geomIter.hasNext()) {
        Geometry geom = geomIter.next();
        if (geom.intersects(srcGeom)) {
            geomIter.remove();
            intersected.add(geom);
        }
    }
    
    // compute the envelope for the intersected geometries and the source geometry, and look for more intersections
    if (!intersected.isEmpty()) {
        intersected.add(srcGeom);
        Geometry mergedGeom = new GeometryCollection(intersected.toArray(new Geometry[intersected.size()]), new GeometryFactory()).getEnvelope();
        return findIntersectedGeoms(mergedGeom, geometries);
    }
    
    return srcGeom;
}
 
Example #2
Source File: SpatialiteWKBWriter.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void write( Geometry geom, OutStream os ) throws IOException {
    buf[0] = 0x69;
    os.write(buf, 1);
    if (geom instanceof Point)
        writePoint((Point) geom, os);
    // LinearRings will be written as LineStrings
    else if (geom instanceof LineString)
        writeLineString((LineString) geom, os);
    else if (geom instanceof Polygon)
        writePolygon((Polygon) geom, os);
    else if (geom instanceof MultiPoint)
        writeGeometryCollection(WKBConstants.wkbMultiPoint, (MultiPoint) geom, os);
    else if (geom instanceof MultiLineString)
        writeGeometryCollection(WKBConstants.wkbMultiLineString, (MultiLineString) geom, os);
    else if (geom instanceof MultiPolygon)
        writeGeometryCollection(WKBConstants.wkbMultiPolygon, (MultiPolygon) geom, os);
    else if (geom instanceof GeometryCollection)
        writeGeometryCollection(WKBConstants.wkbGeometryCollection, (GeometryCollection) geom, os);
    else {
        Assert.shouldNeverReachHere("Unknown Geometry type");
    }
}
 
Example #3
Source File: DxfUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Write a {@link SimpleFeature} to dxf string.
 * 
 * @param featureMate the feature to convert.
 * @param layerName the layer name in case none is in the attributes.
 * @param elevationAttrName the attribute defining elevation or <code>null</code>.
 * @param suffix <code>true</code> if suffix is needed.
 * @param force2CoordsToLine if <code>true</code>, lines that are composed of just 2 coordinates
 *                      will be handled as LINE instead of the default which is POLYLINE.
 * @return the string representation.
 */
public static String feature2Dxf( FeatureMate featureMate, String layerName, String elevationAttrName, boolean suffix,
        boolean force2CoordsToLine ) {
    Geometry g = featureMate.getGeometry();

    if (EGeometryType.isPoint(g)) {
        return point2Dxf(featureMate, layerName, elevationAttrName);
    } else if (EGeometryType.isLine(g)) {
        return lineString2Dxf(featureMate, layerName, elevationAttrName, force2CoordsToLine);
    } else if (EGeometryType.isPolygon(g)) {
        return polygon2Dxf(featureMate, layerName, elevationAttrName, suffix);
    } else if (g instanceof GeometryCollection) {
        StringBuilder sb = new StringBuilder();
        for( int i = 0; i < g.getNumGeometries(); i++ ) {
            SimpleFeature ff = SimpleFeatureBuilder.copy(featureMate.getFeature());
            ff.setDefaultGeometry(g.getGeometryN(i));
            FeatureMate fm = new FeatureMate(ff);
            sb.append(feature2Dxf(fm, layerName, elevationAttrName, suffix, force2CoordsToLine));
        }
        return sb.toString();
    } else {
        return null;
    }
}
 
Example #4
Source File: VectorTileEncoderTest.java    From java-vector-tile with Apache License 2.0 6 votes vote down vote up
public void testGeometryCollection() throws IOException {
    Geometry[] geometries = new Geometry[2];
    geometries[0] = (Polygon) gf.createPoint(new Coordinate(13, 16)).buffer(3);
    geometries[1] = gf.createPoint(new Coordinate(24, 25));
    GeometryCollection gc = gf.createGeometryCollection(geometries);
    Map<String, String> attributes = Collections.singletonMap("key1", "value1");

    VectorTileEncoder vtm = new VectorTileEncoder(256);
    vtm.addFeature("gc", attributes, gc);

    byte[] encoded = vtm.encode();
    assertTrue(encoded.length > 0);

    VectorTileDecoder decoder = new VectorTileDecoder();
    List<Feature> features = decoder.decode(encoded).asList();
    assertEquals(2, features.size());
    assertTrue(features.get(0).getGeometry() instanceof Polygon);
    assertTrue(features.get(1).getGeometry() instanceof Point);
}
 
Example #5
Source File: GeoUtils.java    From elasticsearch-plugin-geoshape with MIT License 6 votes vote down vote up
public static Geometry removeDuplicateCoordinates(Geometry geom) {
    if (geom.isEmpty()) {
        return geom;
    }

    if (geom instanceof Polygon) {
        return removeDuplicateCoordinates((Polygon) geom);
    }

    if (geom instanceof MultiPolygon) {
        return removeDuplicateCoordinates((MultiPolygon) geom);
    }

    if (geom instanceof GeometryCollection) {
        return removeDuplicateCoordinates((GeometryCollection) geom);
    }

    return geom;
}
 
Example #6
Source File: RandomGeometryBuilder.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
public GeometryCollection createRandomGeometryCollection() {
    Geometry[] geometries = new Geometry[numGeometries];
    for (int i=0; i<numGeometries; i++) {
        switch (random.nextInt(3)) {
        case 0:
            geometries[i] = createRandomPoint();
            break;
        case 1:
            geometries[i] = createRandomLineString();
            break;
        default:
            geometries[i] = createRandomPolygon();
        }
    }
    return geometryFactory.createGeometryCollection(geometries);
}
 
Example #7
Source File: ShapeWriter.java    From geopaparazzi with 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 #8
Source File: GeoJSONEncoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
protected ObjectNode encodeGeometry(Geometry geometry, int parentSrid)
        throws JSONEncodingException {
    Preconditions.checkNotNull(geometry);
    if (geometry.isEmpty()) {
        return null;
    } else if (geometry instanceof Point) {
        return encode((Point) geometry, parentSrid);
    } else if (geometry instanceof LineString) {
        return encode((LineString) geometry, parentSrid);
    } else if (geometry instanceof Polygon) {
        return encode((Polygon) geometry, parentSrid);
    } else if (geometry instanceof MultiPoint) {
        return encode((MultiPoint) geometry, parentSrid);
    } else if (geometry instanceof MultiLineString) {
        return encode((MultiLineString) geometry, parentSrid);
    } else if (geometry instanceof MultiPolygon) {
        return encode((MultiPolygon) geometry, parentSrid);
    } else if (geometry instanceof GeometryCollection) {
        return encode((GeometryCollection) geometry, parentSrid);
    } else {
        throw new JSONEncodingException("unknown geometry type " + geometry.getGeometryType());
    }
}
 
Example #9
Source File: GeoFunctions.java    From presto with Apache License 2.0 6 votes vote down vote up
private static void buildPointsBlock(Geometry geometry, BlockBuilder blockBuilder)
{
    GeometryType type = GeometryType.getForJtsGeometryType(geometry.getGeometryType());
    if (type == GeometryType.POINT) {
        GEOMETRY.writeSlice(blockBuilder, JtsGeometrySerde.serialize(geometry));
    }
    else if (type == GeometryType.GEOMETRY_COLLECTION) {
        GeometryCollection collection = (GeometryCollection) geometry;
        for (int i = 0; i < collection.getNumGeometries(); i++) {
            Geometry entry = collection.getGeometryN(i);
            buildPointsBlock(entry, blockBuilder);
        }
    }
    else {
        GeometryFactory geometryFactory = geometry.getFactory();
        Coordinate[] vertices = geometry.getCoordinates();
        for (Coordinate coordinate : vertices) {
            GEOMETRY.writeSlice(blockBuilder, JtsGeometrySerde.serialize(geometryFactory.createPoint(coordinate)));
        }
    }
}
 
Example #10
Source File: GeoJSONUtils.java    From crate with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> convert(Geometry geometry) {
    HashMap<String, Object> builder = new HashMap<>();

    if (geometry instanceof Point) {
        builder.put(TYPE_FIELD, POINT);
        builder.put(COORDINATES_FIELD, extract((Point) geometry));
    } else if (geometry instanceof MultiPoint) {
        builder.put(TYPE_FIELD, MULTI_POINT);
        builder.put(COORDINATES_FIELD, extract((MultiPoint) geometry));
    } else if (geometry instanceof LineString) {
        builder.put(TYPE_FIELD, LINE_STRING);
        builder.put(COORDINATES_FIELD, extract((LineString) geometry));
    } else if (geometry instanceof MultiLineString) {
        builder.put(TYPE_FIELD, MULTI_LINE_STRING);
        builder.put(COORDINATES_FIELD, extract((MultiLineString) geometry));
    } else if (geometry instanceof Polygon) {
        builder.put(TYPE_FIELD, POLYGON);
        builder.put(COORDINATES_FIELD, extract((Polygon) geometry));
    } else if (geometry instanceof MultiPolygon) {
        builder.put(TYPE_FIELD, MULTI_POLYGON);
        builder.put(COORDINATES_FIELD, extract((MultiPolygon) geometry));
    } else if (geometry instanceof GeometryCollection) {
        GeometryCollection geometryCollection = (GeometryCollection) geometry;
        int size = geometryCollection.getNumGeometries();
        List<Map<String, Object>> geometries = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            geometries.add(convert(geometryCollection.getGeometryN(i)));
        }
        builder.put(TYPE_FIELD, GEOMETRY_COLLECTION);
        builder.put(GEOMETRIES_FIELD, geometries);
    } else {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
            "Cannot extract coordinates from geometry %s", geometry.getGeometryType()));
    }
    return Collections.unmodifiableMap(builder);
}
 
Example #11
Source File: GeometryTransform.java    From sis with 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 #12
Source File: TWKBReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
private GeometryCollection readGeometryCollection(final ByteBuffer input, final byte metadata)
    throws ParseException {
  if ((metadata & TWKBUtils.EMPTY_GEOMETRY) != 0) {
    return GeometryUtils.GEOMETRY_FACTORY.createGeometryCollection();
  }
  final int numGeometries = VarintUtils.readUnsignedInt(input);
  final Geometry[] geometries = new Geometry[numGeometries];
  for (int i = 0; i < numGeometries; i++) {
    geometries[i] = read(input);
  }
  return GeometryUtils.GEOMETRY_FACTORY.createGeometryCollection(geometries);
}
 
Example #13
Source File: TWKBWriter.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void writeGeometryCollection(
    final GeometryCollection geoms,
    final PrecisionWriter precision,
    final DataOutput output) throws IOException {
  Varint.writeUnsignedVarInt(geoms.getNumGeometries(), output);
  for (int i = 0; i < geoms.getNumGeometries(); i++) {
    final Geometry geom = geoms.getGeometryN(i);
    write(geom, output);
  }
}
 
Example #14
Source File: HistogramStatistics.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void entryIngested(final GridCoverage entry, final GeoWaveRow... geoWaveRows) {
  /*
   * Create the operation for the Histogram with a ROI. No subsampling should be applied.
   */
  final Geometry footprint;
  if (entry instanceof FitToIndexGridCoverage) {
    footprint = ((FitToIndexGridCoverage) entry).getFootprintWorldGeometry();
    if (footprint == null) {
      return;
    }
  } else {
    // this is a condition that isn't going to be exercised typically in
    // any code, but at this point we will assume default CRS
    footprint = RasterUtils.getFootprint(entry, GeoWaveGTRasterFormat.DEFAULT_CRS);
  }

  final GridCoverage originalCoverage;
  Resolution resolution = null;
  if (entry instanceof FitToIndexGridCoverage) {
    originalCoverage = ((FitToIndexGridCoverage) entry).getOriginalCoverage();
    resolution = ((FitToIndexGridCoverage) entry).getResolution();
  } else {
    originalCoverage = entry;
  }
  if (footprint instanceof GeometryCollection) {
    final GeometryCollection collection = (GeometryCollection) footprint;
    for (int g = 0; g < collection.getNumGeometries(); g++) {
      final Geometry geom = collection.getGeometryN(g);
      if (geom instanceof Polygon) {
        mergePoly(originalCoverage, (Polygon) geom, resolution);
      }
    }
  } else if (footprint instanceof Polygon) {
    mergePoly(originalCoverage, (Polygon) footprint, resolution);
  }
}
 
Example #15
Source File: ShapeWriter.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
private DrawableShape toShape(GeometryCollection gc) {
    GeometryCollectionShape shape = new GeometryCollectionShape();
    // add components to GC shape
    for (int i = 0; i < gc.getNumGeometries(); i++) {
        Geometry g = (Geometry) gc.getGeometryN(i);
        shape.add(toShape(g));
    }
    return shape;
}
 
Example #16
Source File: SpatialiteWKBReader.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private GeometryCollection readGeometryCollection() throws IOException, ParseException {
    int numGeom = dis.readInt();
    Geometry[] geoms = new Geometry[numGeom];
    for( int i = 0; i < numGeom; i++ ) {
        geoms[i] = readGeometry();
    }
    return factory.createGeometryCollection(geoms);
}
 
Example #17
Source File: SpatialiteWKBWriter.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void writeGeometryCollection( int geometryType, GeometryCollection gc, OutStream os ) throws IOException {
    // writeByteOrder(os);
    writeGeometryType(geometryType, gc, os);
    writeInt(gc.getNumGeometries(), os);
    for( int i = 0; i < gc.getNumGeometries(); i++ ) {
        write(gc.getGeometryN(i), os);
    }
}
 
Example #18
Source File: JtsGeometryCollectionIterable.java    From geogson with Apache License 2.0 5 votes vote down vote up
public static JtsGeometryCollectionIterable of(final GeometryCollection src) {
    return new JtsGeometryCollectionIterable(new GeometryProvider() {
        @Override
        public int getNumGeometries() {
            return src.getNumGeometries();
        }

        @Override
        public Geometry getGeometryN(int n) {
            return src.getGeometryN(n);
        }
    });
}
 
Example #19
Source File: GeoJSONTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void testGeometryCollectionWithZCoordinate()
        throws GeoJSONDecodingException, IOException {
    GeometryCollection geometry = geometryFactory.createGeometryCollection(
            new Geometry[] { randomGeometryCollection(EPSG_4326), randomGeometryCollection(2000) });
    geometry.apply(new RandomZCoordinateFilter());
    geometry.geometryChanged();
    readWriteTest(geometry);
}
 
Example #20
Source File: GeoJSONTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
private GeometryCollection randomGeometryCollection(int srid) {
    GeometryCollection geometry = geometryFactory.createGeometryCollection(
            new Geometry[] { randomPoint(srid), randomMultiPoint(srid), randomLineString(srid),
                    randomMultiLineString(srid), randomPolygon(srid), randomMultiPolygon(srid) });
    geometry.setSRID(srid);
    return geometry;
}
 
Example #21
Source File: GeoJSONEncoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
public ObjectNode encode(GeometryCollection geometry, int parentSrid)
        throws JSONEncodingException {
    Preconditions.checkNotNull(geometry);
    ObjectNode json = jsonFactory.objectNode();
    ArrayNode geometries =
            json.put(JSONConstants.TYPE, JSONConstants.GEOMETRY_COLLECTION).putArray(JSONConstants.GEOMETRIES);
    int srid = encodeCRS(json, geometry, parentSrid);
    for (int i = 0; i < geometry.getNumGeometries(); ++i) {
        geometries.add(encodeGeometry(geometry.getGeometryN(i), srid));
    }
    return json;
}
 
Example #22
Source File: GeoJSONDecoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
protected GeometryCollection decodeGeometryCollection(JsonNode node, GeometryFactory fac)
        throws GeoJSONDecodingException {
    final JsonNode geometries = node.path(JSONConstants.GEOMETRIES);
    if (!geometries.isArray()) {
        throw new GeoJSONDecodingException("expected 'geometries' array");
    }
    Geometry[] geoms = new Geometry[geometries.size()];
    for (int i = 0; i < geometries.size(); ++i) {
        geoms[i] = decodeGeometry(geometries.get(i), fac);
    }
    return fac.createGeometryCollection(geoms);
}
 
Example #23
Source File: JTSHelper.java    From arctic-sea with 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 #24
Source File: SpatialiteWKBWriter.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Writes a {@link Geometry} to an {@link OutStream}.
 *
 * @param geom the geometry to write
 * @param os the out stream to write to
 * @throws IOException if an I/O error occurs
 */
public void writeSpatialiteGeometry( Geometry geom, OutStream os ) throws IOException {
    // geom starts with byte 0x00
    buf[0] = 0x00;
    os.write(buf, 1);
    writeByteOrder(os);

    writeInt(geom.getSRID(), os);
    // 6 - 13 MBR_MIN_X a double value [little- big-endian ordered, accordingly with the
    // precedent one]
    // corresponding to the MBR minimum X coordinate for this GEOMETRY
    // 14 - 21 MBR_MIN_Y a double value corresponding to the MBR minimum Y coordinate
    // 22 - 29 MBR_MAX_X a double value corresponding to the MBR maximum X coordinate
    // 30 - 37 MBR_MAX_Y a double value corresponding to the MBR maximum Y coordinate
    Envelope envInt = geom.getEnvelopeInternal();
    writeDouble(envInt.getMinX(), os);
    writeDouble(envInt.getMinY(), os);
    writeDouble(envInt.getMaxX(), os);
    writeDouble(envInt.getMaxY(), os);

    // // 38 MBR_END [hex 7C] a GEOMETRY encoded BLOB value must always have an 0x7C byte in
    // this
    // // position
    buf[0] = 0x7C;
    os.write(buf, 1);

    if (geom instanceof Point)
        writePoint((Point) geom, os);
    // LinearRings will be written as LineStrings
    else if (geom instanceof LineString)
        writeLineString((LineString) geom, os);
    else if (geom instanceof Polygon)
        writePolygon((Polygon) geom, os);
    else if (geom instanceof MultiPoint)
        writeGeometryCollection(WKBConstants.wkbMultiPoint, (MultiPoint) geom, os);
    else if (geom instanceof MultiLineString)
        writeGeometryCollection(WKBConstants.wkbMultiLineString, (MultiLineString) geom, os);
    else if (geom instanceof MultiPolygon)
        writeGeometryCollection(WKBConstants.wkbMultiPolygon, (MultiPolygon) geom, os);
    else if (geom instanceof GeometryCollection)
        writeGeometryCollection(WKBConstants.wkbGeometryCollection, (GeometryCollection) geom, os);
    else {
        Assert.shouldNeverReachHere("Unknown Geometry type");
    }
}
 
Example #25
Source File: OmsVectorIntersector.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inMap1, inMap2);

    outMap = new DefaultFeatureCollection();

    if (!doKeepFirstAttributes) {
        SimpleFeatureCollection inMapTmp = inMap1;
        inMap1 = inMap2;
        inMap2 = inMapTmp;
    }

    List<Geometry> geometries = FeatureUtilities.featureCollectionToGeometriesList(inMap2, false, null);
    GeometryCollection geometryCollection = new GeometryCollection(geometries.toArray(new Geometry[geometries.size()]), gf);
    Geometry intersectionGeometry = geometryCollection.buffer(0);
    PreparedGeometry preparedIntersectionGeometry = PreparedGeometryFactory.prepare(intersectionGeometry);

    List<SimpleFeature> mainFeatures = FeatureUtilities.featureCollectionToList(inMap1);
    if (mainFeatures.size() == 0) {
        throw new ModelsIllegalargumentException("No features found in the layer.", this);
    }

    EGeometryType geometryType = EGeometryType.forGeometry((Geometry) mainFeatures.get(0).getDefaultGeometry());
    Class< ? > multiClazz = geometryType.getMultiClazz();
    EGeometryType newGeometryType = EGeometryType.forClass(multiClazz);
    FeatureGeometrySubstitutor sub = new FeatureGeometrySubstitutor(inMap1.getSchema(), multiClazz);

    pm.beginTask("Performing intersection...", mainFeatures.size());
    for( SimpleFeature feature : mainFeatures ) {
        Geometry geometry = (Geometry) feature.getDefaultGeometry();
        if (preparedIntersectionGeometry.intersects(geometry)) {
            Geometry intersection = geometry.intersection(intersectionGeometry);

            EGeometryType intersectionGeometryType = EGeometryType.forGeometry(intersection);
            if (intersectionGeometryType.isCompatibleWith(newGeometryType)) {
                SimpleFeature newFeature = sub.substituteGeometry(feature, intersection);
                ((DefaultFeatureCollection) outMap).add(newFeature);
            } else {
                pm.errorMessage("Could not add intersection result geometry to layer due to incompatibility: " + intersection);
            }
        }
        pm.worked(1);
    }
    pm.done();

}
 
Example #26
Source File: OmsHoleFiller.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inRaster);

    ISurfaceInterpolator interpolator;
    if (pMode.equals(IDW)) {
        interpolator = new IDWInterpolator(pBuffer);
    } else {
        interpolator = new TPSInterpolator(pBuffer);
    }

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
    int rows = regionMap.getRows();
    int cols = regionMap.getCols();

    WritableRaster outWR = CoverageUtilities.renderedImage2WritableRaster(inRaster.getRenderedImage(), false);
    WritableRandomIter outIter = CoverageUtilities.getWritableRandomIterator(outWR);

    GridGeometry2D gridGeometry = inRaster.getGridGeometry();

    PreparedGeometry preparedRoi = null;
    if (inROI != null) {
        List<Geometry> roiList = FeatureUtilities.featureCollectionToGeometriesList(inROI, false, null);
        GeometryCollection gc = new GeometryCollection(roiList.toArray(GeometryUtilities.TYPE_GEOMETRY), gf);
        preparedRoi = PreparedGeometryFactory.prepare(gc);
    }
    pm.beginTask("Filling holes...", cols - 2);
    for( int r = 1; r < rows - 1; r++ ) {
        for( int c = 1; c < cols - 1; c++ ) {
            if (pm.isCanceled()) {
                return;
            }

            double value = outIter.getSampleDouble(c, r, 0);
            if (isNovalue(value)) {
                DirectPosition worldPosition = gridGeometry.gridToWorld(new GridCoordinates2D(c, r));
                double[] coordinate = worldPosition.getCoordinate();
                Coordinate pointCoordinate = new Coordinate(coordinate[0], coordinate[1]);
                Point point = gf.createPoint(pointCoordinate);
                if (preparedRoi == null || preparedRoi.intersects(point)) {

                    // TODO this could be done considering more points and more far away points.
                    // For now, this works.
                    List<Coordinate> surroundingValids = getValidSurroundingPoints(outIter, gridGeometry, c, r);
                    if (surroundingValids.size() > 3) {
                        double newValue = interpolator.getValue(surroundingValids.toArray(new Coordinate[0]),
                                pointCoordinate);
                        outIter.setSample(c, r, 0, newValue);
                    }
                }
            }
        }
        pm.worked(1);
    }
    pm.done();

    outIter.done();

    outRaster = CoverageUtilities.buildCoverage("nulled", outWR, regionMap, inRaster.getCoordinateReferenceSystem());
}
 
Example #27
Source File: SimpleFeatureShapeFigureTest.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private GeometryCollection createGeometryCollection() {
    return gf.createGeometryCollection(new Geometry[0]);
}
 
Example #28
Source File: VectorTileEncoder.java    From java-vector-tile with Apache License 2.0 4 votes vote down vote up
/**
 * Add a feature with layer name (typically feature type name), some attributes
 * and a Geometry. The Geometry must be in "pixel" space 0,0 upper left and
 * 256,256 lower right.
 * <p>
 * For optimization, geometries will be clipped and simplified. Features with
 * geometries outside of the tile will be skipped.
 *
 * @param layerName
 * @param attributes
 * @param geometry
 * @param id
 */
public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry, long id) {

    // skip small Polygon/LineString.
    if (geometry instanceof MultiPolygon && geometry.getArea() < minimumArea) {
        return;
    }
    if (geometry instanceof Polygon && geometry.getArea() < minimumArea) {
        return;
    }
    if (geometry instanceof LineString && geometry.getLength() < minimumLength) {
        return;
    }

    // special handling of GeometryCollection. subclasses are not handled here.
    if (geometry.getClass().equals(GeometryCollection.class)) {
        for (int i = 0; i < geometry.getNumGeometries(); i++) {
            Geometry subGeometry = geometry.getGeometryN(i);
            // keeping the id. any better suggestion?
            addFeature(layerName, attributes, subGeometry, id);
        }
        return;
    }

    // clip geometry
    if (geometry instanceof Point) {
        if (!clipCovers(geometry)) {
            return;
        }
    } else {
        geometry = clipGeometry(geometry);
    }
    
    // simplify non-points
    if (simplificationDistanceTolerance > 0.0 && !(geometry instanceof Point)) {
        geometry = TopologyPreservingSimplifier.simplify(geometry, simplificationDistanceTolerance);
    }

    // no need to add empty geometry
    if (geometry.isEmpty()) {
        return;
    }

    Layer layer = layers.get(layerName);
    if (layer == null) {
        layer = new Layer();
        layers.put(layerName, layer);
    }

    Feature feature = new Feature();
    feature.geometry = geometry;
    feature.id = id;
    this.autoincrement = Math.max(this.autoincrement, id + 1);

    for (Map.Entry<String, ?> e : attributes.entrySet()) {
        // skip attribute without value
        if (e.getValue() == null) {
            continue;
        }
        feature.tags.add(layer.key(e.getKey()));
        feature.tags.add(layer.value(e.getValue()));
    }

    layer.features.add(feature);
}
 
Example #29
Source File: ElasticParserUtilTest.java    From elasticgeo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testGeoShapeGeometryCollectionWkt() {
    rgb.setNumGeometries(5);
    GeometryCollection geom = rgb.createRandomGeometryCollection();
    assertTrue(parserUtil.createGeometry(rgb.toWkt(geom)).equalsExact(geom, 1e-9));
}
 
Example #30
Source File: TWKBWriter.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void write(final Geometry geom, final DataOutput output) throws IOException {
  final byte type = getType(geom);
  if (geom.isEmpty()) {
    output.writeByte(getTypeAndPrecisionByte(type, 0));
    output.writeByte(TWKBUtils.EMPTY_GEOMETRY);
    return;
  }
  byte metadata = 0;
  final Coordinate[] coordinates = geom.getCoordinates();
  PrecisionWriter precision;
  if (Double.isNaN(coordinates[0].getZ()) || Double.isNaN(coordinates[0].getM())) {
    metadata |= TWKBUtils.EXTENDED_DIMENSIONS;
    precision = new ExtendedPrecisionWriter().calculate(coordinates, maxPrecision);
  } else {
    precision = new PrecisionWriter().calculate(coordinates, maxPrecision);
  }
  output.writeByte(getTypeAndPrecisionByte(type, precision.precision));
  output.writeByte(metadata);
  precision.writeExtendedPrecision(output);

  switch (type) {
    case TWKBUtils.POINT_TYPE:
      writePoint((Point) geom, precision, output);
      break;
    case TWKBUtils.LINESTRING_TYPE:
      writeLineString((LineString) geom, precision, output);
      break;
    case TWKBUtils.POLYGON_TYPE:
      writePolygon((Polygon) geom, precision, output);
      break;
    case TWKBUtils.MULTIPOINT_TYPE:
      writeMultiPoint((MultiPoint) geom, precision, output);
      break;
    case TWKBUtils.MULTILINESTRING_TYPE:
      writeMultiLineString((MultiLineString) geom, precision, output);
      break;
    case TWKBUtils.MULTIPOLYGON_TYPE:
      writeMultiPolygon((MultiPolygon) geom, precision, output);
      break;
    case TWKBUtils.GEOMETRYCOLLECTION_TYPE:
      writeGeometryCollection((GeometryCollection) geom, precision, output);
      break;
    default:
      break;
  }
}