org.locationtech.jts.geom.Geometry类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(15.9k)|赞(0)|评价(0)|浏览(1756)

本文整理了Java中org.locationtech.jts.geom.Geometry类的一些代码示例,展示了Geometry类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Geometry类的具体详情如下:
包路径:org.locationtech.jts.geom.Geometry
类名称:Geometry

Geometry介绍

[英]A representation of a planar, linear vector geometry.

Binary Predicates

Because it is not clear at this time what semantics for spatial analysis methods involving GeometryCollections would be useful, GeometryCollections are not supported as arguments to binary predicates or the relate method.

Overlay Methods

The overlay methods return the most specific class possible to represent the result. If the result is homogeneous, a Point, LineString, or Polygon will be returned if the result contains a single element; otherwise, a MultiPoint, MultiLineString, or MultiPolygon will be returned. If the result is heterogeneous a GeometryCollection will be returned.

Because it is not clear at this time what semantics for set-theoretic methods involving GeometryCollections would be useful, GeometryCollections are not supported as arguments to the set-theoretic methods.

Representation of Computed Geometries

The SFS states that the result of a set-theoretic method is the "point-set" result of the usual set-theoretic definition of the operation (SFS 3.2.21.1). However, there are sometimes many ways of representing a point set as a Geometry.

The SFS does not specify an unambiguous representation of a given point set returned from a spatial analysis method. One goal of JTS is to make this specification precise and unambiguous. JTS uses a canonical form for Geometrys returned from overlay methods. The canonical form is a Geometry which is simple and noded:

  • Simple means that the Geometry returned will be simple according to the JTS definition of isSimple.
  • Noded applies only to overlays involving LineStrings. It means that all intersection points on LineStrings will be present as endpoints of LineStrings in the result.
    This definition implies that non-simple geometries which are arguments to spatial analysis methods must be subjected to a line-dissolve process to ensure that the results are simple.
Constructed Points And The Precision Model

The results computed by the set-theoretic methods may contain constructed points which are not present in the input Geometry s. These new points arise from intersections between line segments in the edges of the input Geometrys. In the general case it is not possible to represent constructed points exactly. This is due to the fact that the coordinates of an intersection point may contain twice as many bits of precision as the coordinates of the input line segments. In order to represent these constructed points explicitly, JTS must truncate them to fit the PrecisionModel.

Unfortunately, truncating coordinates moves them slightly. Line segments which would not be coincident in the exact result may become coincident in the truncated representation. This in turn leads to "topology collapses" -- situations where a computed element has a lower dimension than it would in the exact result.

When JTS detects topology collapses during the computation of spatial analysis methods, it will throw an exception. If possible the exception will report the location of the collapse.

Geometry Equality

There are two ways of comparing geometries for equality: structural equality and topological equality.

Structural Equality

Structural Equality is provided by the #equalsExact(Geometry) method. This implements a comparison based on exact, structural pointwise equality. The #equals(Object) is a synonym for this method, to provide structural equality semantics for use in Java collections. It is important to note that structural pointwise equality is easily affected by things like ring order and component order. In many situations it will be desirable to normalize geometries before comparing them (using the #norm() or #normalize() methods). #equalsNorm(Geometry) is provided as a convenience method to compute equality over normalized geometries, but it is expensive to use. Finally, #equalsExact(Geometry,double)allows using a tolerance value for point comparison.

Topological Equality

Topological Equality is provided by the #equalsTopo(Geometry) method. It implements the SFS definition of point-set equality defined in terms of the DE-9IM matrix. To support the SFS naming convention, the method #equals(Geometry) is also provided as a synonym. However, due to the potential for confusion with #equals(Object)its use is discouraged.

Since #equals(Object) and #hashCode() are overridden, Geometries can be used effectively in Java collections.
[中]平面线性向量几何体的表示。
####二元谓词
由于目前尚不清楚涉及GeometryCollections的空间分析方法的语义是否有用,因此不支持将GeometryCollections作为二进制谓词或relate方法的参数。
####叠加法
overlay方法返回可能表示结果的最特定类。如果结果是同构的,则如果结果包含单个元素,将返回PointLineStringPolygon;否则,将返回MultiPointMultiLineStringMultiPolygon。如果结果是异构的,将返回GeometryCollection
由于目前尚不清楚涉及GeometryCollections的集合论方法的语义是什么,因此不支持GeometryCollections作为集合论方法的参数。
#####计算几何图形的表示
SFS规定,集合论方法的结果是操作的常用集合论定义的“点集”结果(SFS 3.2.21.1)。但是,有时有许多方法可以将点集表示为Geometry
SFS未指定从空间分析方法返回的给定点集的明确表示形式。JTS的一个目标是使该规范准确无误。JTS对从覆盖方法返回的Geometrys使用规范形式。标准形式为Geometry,简单且有点:
*简单意味着根据JTS定义isSimple,返回的几何体将是简单的。
*Noded仅适用于涉及LineStrings的覆盖。这意味着LineStrings上的所有交点将作为LineStrings的端点出现在结果中。
该定义意味着,作为空间分析方法参数的非简单几何体必须经过线溶解过程,以确保结果简单。
#####构造点与精度模型
通过集合论方法计算的结果可能包含输入Geometrys中不存在的构造点。这些新点产生于输入Geometrys边缘的线段之间的交点。在一般情况下,不可能精确表示构造点。这是因为交点的坐标可能包含两倍于输入线段坐标的精度位。为了显式表示这些构造点,JTS必须截断它们以适应PrecisionModel
不幸的是,截断坐标会稍微移动它们。在精确结果中不重合的线段可能在截断表示中重合。这进而导致“拓扑崩溃”——即计算元素的维数低于精确结果的维数。
当JTS在空间分析方法的计算过程中检测到拓扑崩溃时,它将抛出异常。如果可能,异常将报告崩溃的位置。
####几何相等
有两种比较几何相等的方法:结构相等和拓扑相等。
#####结构平等
结构等式由#equalsExact(几何)方法提供。这实现了基于精确的、结构化的逐点相等的比较。#equals(Object)是该方法的同义词,用于提供Java集合中使用的结构相等语义。需要注意的是,结构的逐点相等很容易受到环序和分量序等因素的影响。在许多情况下,需要在比较几何图形之前对其进行规格化(使用#norm()或#normalize()方法)#equalsNorm(Geometry)是作为一种方便的方法提供的,用于计算规范化几何体上的等式,但使用起来很昂贵。最后,#equalsExact(几何体,双精度)允许使用公差值进行点比较。
#####拓扑等式
拓扑等式由#equalsTopo(几何)方法提供。它实现了根据DE-9IM矩阵定义的SFS点集等式定义。为了支持SFS命名约定,还提供了方法#equals(几何体)作为同义词。但是,由于可能与#equals(Object)混淆,因此不鼓励使用它。
由于#equals(Object)和#hashCode()被重写,因此可以在Java集合中有效地使用几何体。

代码示例

代码示例来源:origin: com.h2database/h2

/**
 * Test if this geometry envelope intersects with the other geometry
 * envelope.
 *
 * @param r the other geometry
 * @return true if the two overlap
 */
public boolean intersectsBoundingBox(ValueGeometry r) {
  // the Geometry object caches the envelope
  return getGeometryNoCopy().getEnvelopeInternal().intersects(
      r.getGeometryNoCopy().getEnvelopeInternal());
}

代码示例来源:origin: prestodb/presto

@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();
}

代码示例来源:origin: prestodb/presto

private static void writePolyline(Geometry geometry, SliceOutput output, boolean multitype)
{
  int numParts;
  int numPoints = geometry.getNumPoints();
  if (multitype) {
    numParts = geometry.getNumGeometries();
    output.writeByte(GeometrySerializationType.MULTI_LINE_STRING.code());
  }
  else {
    numParts = numPoints > 0 ? 1 : 0;
    output.writeByte(GeometrySerializationType.LINE_STRING.code());
  }
  output.writeInt(EsriShapeType.POLYLINE.code);
  writeEnvelope(geometry, output);
  output.writeInt(numParts);
  output.writeInt(numPoints);
  int partIndex = 0;
  for (int i = 0; i < numParts; i++) {
    output.writeInt(partIndex);
    partIndex += geometry.getGeometryN(i).getNumPoints();
  }
  writeCoordinates(geometry.getCoordinates(), output);
}

代码示例来源:origin: hibernate/hibernate-orm

private boolean testVerticesEquality(Geometry geom1, Geometry geom2) {
    if ( geom1.getNumPoints() != geom2.getNumPoints() ) {
      return false;
    }
    for ( int i = 0; i < geom1.getNumPoints(); i++ ) {
      Coordinate cn1 = geom1.getCoordinates()[i];
      Coordinate cn2 = geom2.getCoordinates()[i];
      if ( !cn1.equals2D( cn2 ) ) {
        return false;
      }
    }
    return true;
  }
}

代码示例来源:origin: hibernate/hibernate-orm

protected boolean testTypeAndVertexEquality(Geometry geom1, Geometry geom2) {
  if ( !geom1.getGeometryType().equals( geom2.getGeometryType() ) ) {
    return false;
  }
  if ( geom1.getNumGeometries() != geom2.getNumGeometries() ) {
    return false;
  }
  if ( geom1.getNumPoints() != geom2.getNumPoints() ) {
    return false;
  }
  Coordinate[] coordinates1 = geom1.getCoordinates();
  Coordinate[] coordinates2 = geom2.getCoordinates();
  for ( int i = 0; i < coordinates1.length; i++ ) {
    Coordinate c1 = coordinates1[i];
    Coordinate c2 = coordinates2[i];
    if ( !testCoordinateEquality( c1, c2 ) ) {
      return false;
    }
  }
  return true;
}

代码示例来源:origin: geotools/geotools

private Geometry clipToWorldFeatureTypeGeometry(Geometry geom) {
  // Oracle cannot deal with filters using geometries that span beyond the whole world
  if (isFeatureTypeGeometryGeodetic() && !WORLD.contains(geom.getEnvelopeInternal())) {
    Geometry result = geom.intersection(JTS.toGeometry(WORLD));
    if (result != null && !result.isEmpty()) {
      if (result instanceof GeometryCollection) {
        result = distillSameTypeGeometries((GeometryCollection) result, geom);
      }
      return result;
    }
  }
  return geom;
}

代码示例来源:origin: geotools/geotools

@Test
public void smoothLinearRing() {
  Coordinate[] coords = getPolyCoords();
  LineString line = factory.createLinearRing(coords);
  Geometry smoothed = JTS.smooth(line, 0);
  assertTrue(smoothed instanceof LinearRing);
  CoordList list = new CoordList(smoothed.getCoordinates());
  assertTrue(list.containsAll(coords));
  Envelope lineEnv = line.getEnvelopeInternal();
  Envelope smoothEnv = smoothed.getEnvelopeInternal();
  assertTrue(smoothEnv.covers(lineEnv));
}

代码示例来源:origin: hibernate/hibernate-orm

@Override
public boolean test(Geometry geom1, Geometry geom2) {
  if ( geom1 != null && geom1.isEmpty() ) {
    return geom2 == null || geom2.isEmpty();
  }
  return super.test( geom1, geom2 );
}

代码示例来源:origin: prestodb/presto

private static void writeGeometryCollection(Geometry collection, DynamicSliceOutput output)
{
  output.appendByte(GeometrySerializationType.GEOMETRY_COLLECTION.code());
  for (int geometryIndex = 0; geometryIndex < collection.getNumGeometries(); geometryIndex++) {
    Geometry geometry = collection.getGeometryN(geometryIndex);
    int startPosition = output.size();
    // leave 4 bytes for the shape length
    output.appendInt(0);
    writeGeometry(geometry, output);
    int endPosition = output.size();
    int length = endPosition - startPosition - Integer.BYTES;
    output.getUnderlyingSlice().setInt(startPosition, length);
  }
}

代码示例来源:origin: geotools/geotools

clipped = clipper.clip(geom, true);
} else {
  if (geom.getEnvelopeInternal().intersects(clip.getEnvelopeInternal())) {
    clipped = clip.intersection(geom);
    new GeometryDimensionCollector(geom.getDimension());
clipped.apply(collector);
Geometry result = collector.collect();
if (result == null) {
if (preserveZ && !geom.equalsExact(clipped)) {
  if (result.getDimension() == 2 || result.getDimension() == 0) {
    result.apply(new IDWElevationInterpolator(geom, crs));
  } else if (result.getDimension() == 1) {
    result.apply(new LinearElevationInterpolator(geom, crs));

代码示例来源:origin: locationtech/spatial4j

/**
 * This "pages" through standard geo boundaries offset by multiples of 360
 * longitudinally that intersect geom, and the intersecting results of a page
 * and the geom are shifted into the standard -180 to +180 and added to a new
 * geometry that is returned.
 */
private static Geometry cutUnwrappedGeomInto360(Geometry geom) {
 Envelope geomEnv = geom.getEnvelopeInternal();
 if (geomEnv.getMinX() >= -180 && geomEnv.getMaxX() <= 180)
  return geom;
 assert geom.isValid() : "geom";
 //TODO opt: support geom's that start at negative pages --
 // ... will avoid need to previously shift in unwrapDateline(geom).
 List<Geometry> geomList = new ArrayList<Geometry>();
 //page 0 is the standard -180 to 180 range
 for (int page = 0; true; page++) {
  double minX = -180 + page * 360;
  if (geomEnv.getMaxX() <= minX)
   break;
  Geometry rect = geom.getFactory().toGeometry(new Envelope(minX, minX + 360, -90, 90));
  assert rect.isValid() : "rect";
  Geometry pageGeom = rect.intersection(geom);//JTS is doing some hard work
  assert pageGeom.isValid() : "pageGeom";
  shiftGeomByX(pageGeom, page * -360);
  geomList.add(pageGeom);
 }
 return UnaryUnionOp.union(geomList);
}

代码示例来源:origin: prestodb/presto

private static void writeEnvelope(Geometry geometry, SliceOutput output)
{
  if (geometry.isEmpty()) {
    for (int i = 0; i < 4; i++) {
      output.writeDouble(NaN);
    }
    return;
  }
  Envelope envelope = geometry.getEnvelopeInternal();
  output.writeDouble(envelope.getMinX());
  output.writeDouble(envelope.getMinY());
  output.writeDouble(envelope.getMaxX());
  output.writeDouble(envelope.getMaxY());
}

代码示例来源:origin: geotools/geotools

public static ReferencedEnvelope reprojectEnvelope(
    ReferencedEnvelope sourceEnvelope,
    CoordinateReferenceSystem targetCRS,
    ReferencedEnvelope targetReferenceEnvelope)
    throws FactoryException, TransformException {
  Geometry reprojected =
      Utils.reprojectEnvelopeToGeometry(
          sourceEnvelope, targetCRS, targetReferenceEnvelope);
  if (reprojected == null) {
    return new ReferencedEnvelope(targetCRS);
  } else {
    if (reprojected.getNumGeometries() > 1) {
      return new ReferencedEnvelope(
          reprojected.getGeometryN(0).getEnvelopeInternal(), targetCRS);
    } else {
      return new ReferencedEnvelope(reprojected.getEnvelopeInternal(), targetCRS);
    }
  }
}

代码示例来源:origin: geotools/geotools

@Test
public void smoothMultiLineString() {
  LineString[] lines = new LineString[3];
  lines[0] = factory.createLineString(getLineCoords(0));
  lines[1] = factory.createLineString(getLineCoords(10));
  lines[2] = factory.createLineString(getLineCoords(20));
  MultiLineString mls = factory.createMultiLineString(lines);
  Geometry smoothed = JTS.smooth(mls, 0);
  assertTrue(smoothed instanceof MultiLineString);
  assertEquals(3, smoothed.getNumGeometries());
  Envelope mlsEnv = mls.getEnvelopeInternal();
  Envelope smoothEnv = smoothed.getEnvelopeInternal();
  assertTrue(smoothEnv.covers(mlsEnv));
}

代码示例来源:origin: geotools/geotools

/**
 * Tests if a specified {@link Point2D}is inside the boundary of the <code>Shape</code>.
 *
 * @param p a specified <code>Point2D</code>
 * @return <code>true</code> if the specified <code>Point2D</code> is inside the boundary of the
 *     <code>Shape</code>; <code>false</code> otherwise.
 */
public boolean contains(Point2D p) {
  Coordinate coord = new Coordinate(p.getX(), p.getY());
  Geometry point = geometry.getFactory().createPoint(coord);
  return geometry.contains(point);
}

代码示例来源:origin: geotools/geotools

private void initCRS(Geometry g) {
    // see if we have a native CRS in the mix
    if (crs == null && g.getUserData() instanceof CoordinateReferenceSystem) {
      crs = (CoordinateReferenceSystem) g.getUserData();
    }
    if (srid == -1 && g.getSRID() > 0) {
      srid = g.getSRID();
    }
  }
}

代码示例来源:origin: geotools/geotools

@Override
protected void visitLiteralGeometry(Literal expression) throws IOException {
  Geometry g = (Geometry) evaluateLiteral(expression, Geometry.class);
  if (g instanceof LinearRing) {
    // WKT does not support linear rings
    g = g.getFactory().createLineString(((LinearRing) g).getCoordinateSequence());
  }
  out.write("ST_GeomFromText('" + g.toText() + "', " + currentSRID + ")");
}

代码示例来源:origin: geotools/geotools

@Override
public void filter(Geometry gmtr) {
  if (MultiPolygon.class.isAssignableFrom(binding)) {
    if (gmtr.getArea() != 0.0d && gmtr.getGeometryType().equals("Polygon")) {
      collection.add(gmtr);
    }
  }
  if (MultiLineString.class.isAssignableFrom(binding)) {
    if (gmtr.getLength() != 0.0d && gmtr.getGeometryType().equals("LineString")) {
      collection.add(gmtr);
    }
  }
  if (MultiPoint.class.isAssignableFrom(binding)) {
    if (gmtr.getNumGeometries() > 0 && gmtr.getGeometryType().equals("Point")) {
      collection.add(gmtr);
    }
  }
  if (Point.class.isAssignableFrom(binding)) {
    if (gmtr.getGeometryType().equals("Point")) {
      collection.add(gmtr);
    }
  }
}

代码示例来源:origin: geotools/geotools

@Override
public ROI intersect(ROI roi) {
  final Geometry geom = getGeometry(roi);
  // is it a rectangle?
  if (geom != null && geom.equalsExact(geom.getEnvelope())) {
    GeometryClipper clipper = new GeometryClipper(geom.getEnvelopeInternal());
    Geometry intersect = clipper.clip(getAsGeometry(), true);
    return new ROIGeometry(intersect);
  } else {
    return super.intersect(roi);
  }
}

代码示例来源:origin: com.h2database/h2

private static int getDimensionCount(Geometry geometry) {
  ZVisitor finder = new ZVisitor();
  geometry.apply(finder);
  return finder.isFoundZ() ? 3 : 2;
}

相关文章

微信公众号

最新文章

更多