Java Code Examples for org.locationtech.jts.geom.Geometry#isEmpty()

The following examples show how to use org.locationtech.jts.geom.Geometry#isEmpty() . 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: ExtractGeometryFilterVisitor.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * @param filter
 * @param crs
 * @return null if empty constraint (infinite not supported)
 */
public static ExtractGeometryFilterVisitorResult getConstraints(
    final Filter filter,
    final CoordinateReferenceSystem crs,
    final String attributeOfInterest) {
  final ExtractGeometryFilterVisitorResult geoAndCompareOpData =
      (ExtractGeometryFilterVisitorResult) filter.accept(
          new ExtractGeometryFilterVisitor(crs, attributeOfInterest),
          null);
  if (geoAndCompareOpData == null) {
    return null;
  }
  final Geometry geo = geoAndCompareOpData.getGeometry();
  // empty or infinite geometry simply return null as we can't create
  // linear constraints from
  if ((geo == null) || geo.isEmpty()) {
    return null;
  }
  final double area = geo.getArea();
  if (Double.isInfinite(area) || Double.isNaN(area)) {
    return null;
  }
  return geoAndCompareOpData;
}
 
Example 2
Source File: BasicMapReduceIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
protected void mapNativeValue(
    final GeoWaveInputKey key,
    final Object value,
    final Mapper<GeoWaveInputKey, ObjectWritable, NullWritable, NullWritable>.Context context)
    throws IOException, InterruptedException {
  ResultCounterType resultType = ResultCounterType.ERROR;
  if (value instanceof SimpleFeature) {
    final SimpleFeature result = (SimpleFeature) value;
    final Geometry geometry = (Geometry) result.getDefaultGeometry();
    if (!geometry.isEmpty()) {
      resultType =
          expectedHashedCentroids.contains(TestUtils.hashCentroid(geometry))
              ? ResultCounterType.EXPECTED
              : ResultCounterType.UNEXPECTED;
    }
  }
  context.getCounter(resultType).increment(1);
}
 
Example 3
Source File: DBScanClusterList.java    From geowave with Apache License 2.0 6 votes vote down vote up
protected double interpolateFactor(final Geometry areaBeingMerged) {
  try {
    if (clusterGeo == null) {
      return 1.0;
    }
    final Geometry intersection = areaBeingMerged.intersection(clusterGeo);
    final double geo2Area = areaBeingMerged.getArea();
    if (intersection != null) {
      if ((intersection instanceof Point) && (areaBeingMerged instanceof Point)) {
        return 0.0;
      } else if (intersection.isEmpty()) {
        return 1.0;
      } else if (geo2Area > 0) {
        return 1.0 - (intersection.getArea() / geo2Area);
      } else {
        return 0.0;
      }
    }
    return 1.0;
  } catch (final Exception ex) {
    LOGGER.warn("Cannot calculate difference of geometries to interpolate size ", ex);
  }
  return 0.0;
}
 
Example 4
Source File: VectorTileEncoder.java    From java-vector-tile with Apache License 2.0 6 votes vote down vote up
/**
 * Clip geometry according to buffer given at construct time. This method
 * can be overridden to change clipping behavior. See also
 * {@link #clipCovers(Geometry)}.
 *
 * @param geometry
 * @return
 */
protected Geometry clipGeometry(Geometry geometry) {
    try {
        Geometry original = geometry;
        geometry = clipGeometry.intersection(original);

        // some times a intersection is returned as an empty geometry.
        // going via wkt fixes the problem.
        if (geometry.isEmpty() && original.intersects(clipGeometry)) {
            Geometry originalViaWkt = new WKTReader().read(original.toText());
            geometry = clipGeometry.intersection(originalViaWkt);
        }

        return geometry;
    } catch (TopologyException e) {
        // could not intersect. original geometry will be used instead.
        return geometry;
    } catch (ParseException e1) {
        // could not encode/decode WKT. original geometry will be used
        // instead.
        return geometry;
    }
}
 
Example 5
Source File: FeatureBoundingBoxStatistics.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
protected Envelope getEnvelope(final SimpleFeature entry) {
  // incorporate the bounding box of the entry's envelope
  final Object o;
  if ((reprojectedType != null)
      && (transform != null)
      && !reprojectedType.getCoordinateReferenceSystem().equals(
          entry.getType().getCoordinateReferenceSystem())) {
    o =
        GeometryUtils.crsTransform(entry, reprojectedType, transform).getAttribute(
            getFieldName());
  } else {
    o = entry.getAttribute(getFieldName());
  }
  if ((o != null) && (o instanceof Geometry)) {
    final Geometry geometry = (Geometry) o;
    if (!geometry.isEmpty()) {
      return geometry.getEnvelopeInternal();
    }
  }
  return null;
}
 
Example 6
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 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: GeoFunctions.java    From presto with Apache License 2.0 6 votes vote down vote up
@SqlNullable
@Description("Returns a float between 0 and 1 representing the location of the closest point on the LineString to the given Point, as a fraction of total 2d line length.")
@ScalarFunction("line_locate_point")
@SqlType(DOUBLE)
public static Double lineLocatePoint(@SqlType(GEOMETRY_TYPE_NAME) Slice lineSlice, @SqlType(GEOMETRY_TYPE_NAME) Slice pointSlice)
{
    Geometry line = JtsGeometrySerde.deserialize(lineSlice);
    Geometry point = JtsGeometrySerde.deserialize(pointSlice);

    if (line.isEmpty() || point.isEmpty()) {
        return null;
    }

    GeometryType lineType = GeometryType.getForJtsGeometryType(line.getGeometryType());
    if (lineType != GeometryType.LINE_STRING && lineType != GeometryType.MULTI_LINE_STRING) {
        throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("First argument to line_locate_point must be a LineString or a MultiLineString. Got: %s", line.getGeometryType()));
    }

    GeometryType pointType = GeometryType.getForJtsGeometryType(point.getGeometryType());
    if (pointType != GeometryType.POINT) {
        throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Second argument to line_locate_point must be a Point. Got: %s", point.getGeometryType()));
    }

    return new LengthIndexedLine(line).indexOf(point.getCoordinate()) / line.getLength();
}
 
Example 9
Source File: JtsSpatialAlgebra.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Shape symDifference(Shape s1, Shape s2) {
	Geometry symDiff = shapeFactory.getGeometryFrom(s1).symDifference(shapeFactory.getGeometryFrom(s2));
	if (symDiff.isEmpty()) {
		return shapeFactory.pointXY(Double.NaN, Double.NaN);
	}
	return shapeFactory.makeShapeFromGeometry(symDiff);
}
 
Example 10
Source File: FilterToElasticHelper.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if the geometry is fully empty
 * @param geometry Geometry
 * @return Flag indicating whether geometry is empty
 */
private boolean isEmpty(Literal geometry) {
    boolean result = false;
    if(geometry != null) {
        Geometry g = geometry.evaluate(null, Geometry.class);
        result = g == null || g.isEmpty();
    }
    return result;
}
 
Example 11
Source File: GeoShapeAggregator.java    From elasticsearch-plugin-geoshape with MIT License 5 votes vote down vote up
private Geometry simplifyGeoShape(Geometry geom) {
    Geometry polygonSimplified = getSimplifiedShape(geom);
    if (polygonSimplified.isEmpty()) {
        polygonSimplified = this.geometryFactory.createPoint(geom.getCoordinate());
    }
    return polygonSimplified;
}
 
Example 12
Source File: RasterUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static Geometry getFootprint(
    final ReferencedEnvelope projectedReferenceEnvelope,
    final GridCoverage gridCoverage) {
  try {
    final Envelope sampleEnvelope = gridCoverage.getEnvelope();
    final double avgSpan =
        (projectedReferenceEnvelope.getSpan(0) + projectedReferenceEnvelope.getSpan(1)) / 2;
    final MathTransform gridCrsToWorldCrs =
        CRS.findMathTransform(
            gridCoverage.getCoordinateReferenceSystem(),
            projectedReferenceEnvelope.getCoordinateReferenceSystem(),
            true);
    final Coordinate[] polyCoords =
        getWorldCoordinates(
            sampleEnvelope.getMinimum(0),
            sampleEnvelope.getMinimum(1),
            sampleEnvelope.getMaximum(0),
            sampleEnvelope.getMaximum(1),
            gridCrsToWorldCrs.isIdentity() ? 2
                : (int) Math.min(
                    Math.max((avgSpan * MIN_SEGMENTS) / SIMPLIFICATION_MAX_DEGREES, MIN_SEGMENTS),
                    MAX_SEGMENTS),
            gridCrsToWorldCrs);
    final Polygon poly = new GeometryFactory().createPolygon(polyCoords);
    if (polyCoords.length > MAX_VERTICES_BEFORE_SIMPLIFICATION) {
      final Geometry retVal = DouglasPeuckerSimplifier.simplify(poly, SIMPLIFICATION_MAX_DEGREES);
      if (retVal.isEmpty()) {
        return poly;
      }
      return retVal;
    } else {
      return poly;
    }
  } catch (MismatchedDimensionException | TransformException | FactoryException e1) {
    LOGGER.warn("Unable to calculate grid coverage footprint", e1);
  }
  return null;
}
 
Example 13
Source File: AccumuloDataStoreStatsTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
protected Envelope getEnvelope(final TestGeometry entry) {
  // incorporate the bounding box of the entry's envelope
  final Geometry geometry = entry.geom;
  if ((geometry != null) && !geometry.isEmpty()) {
    return geometry.getEnvelopeInternal();
  }
  return null;
}
 
Example 14
Source File: AbstractGeoWaveBasicVectorIT.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void entryIngested(final SimpleFeature entry, final GeoWaveRow... geowaveRows) {
  for (final InternalDataStatistics<SimpleFeature, ?, ?> stats : statsCache.values()) {
    stats.entryIngested(entry, geowaveRows);
  }
  final Geometry geometry = ((Geometry) entry.getDefaultGeometry());
  if ((geometry != null) && !geometry.isEmpty()) {
    minX = Math.min(minX, geometry.getEnvelopeInternal().getMinX());
    minY = Math.min(minY, geometry.getEnvelopeInternal().getMinY());
    maxX = Math.max(maxX, geometry.getEnvelopeInternal().getMaxX());
    maxY = Math.max(maxY, geometry.getEnvelopeInternal().getMaxY());
  }
}
 
Example 15
Source File: GeometryUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a longitude range from a JTS geometry
 *
 * @param geometry The JTS geometry
 * @return The x range
 */
public static NumericData xRangeFromGeometry(final Geometry geometry) {
  if ((geometry == null) || geometry.isEmpty()) {
    return new NumericRange(0, 0);
  }
  // Get the envelope of the geometry being held
  final Envelope env = geometry.getEnvelopeInternal();

  // Create a NumericRange object using the x axis
  return new NumericRange(env.getMinX(), env.getMaxX());
}
 
Example 16
Source File: GeometryUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a latitude range from a JTS geometry
 *
 * @param geometry The JTS geometry
 * @return The y range
 */
public static NumericData yRangeFromGeometry(final Geometry geometry) {
  if ((geometry == null) || geometry.isEmpty()) {
    return new NumericRange(0, 0);
  }
  // Get the envelope of the geometry being held
  final Envelope env = geometry.getEnvelopeInternal();

  // Create a NumericRange object using the y axis
  return new NumericRange(env.getMinY(), env.getMaxY());
}
 
Example 17
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 18
Source File: JTSHelper.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public static boolean isNotEmpty(Geometry geometry) {
    return geometry != null && !geometry.isEmpty();
}
 
Example 19
Source File: GeometrySimpOptionProvider.java    From geowave with Apache License 2.0 4 votes vote down vote up
public boolean filterGeometry(final Geometry geom) {
  return ((geom.getCoordinates().length < maxVertices) && !geom.isEmpty() && geom.isValid());
}
 
Example 20
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;
  }
}