Tabnine Logo
Geometry
Code IndexAdd Tabnine to your IDE (free)

How to use
Geometry
in
com.vividsolutions.jts.geom

Best Java code snippets using com.vividsolutions.jts.geom.Geometry (Showing top 20 results out of 2,313)

Refine searchRefine arrow

  • GeometryFactory
  • Envelope
  • SimpleFeature
  • SimpleFeatureCollection
  • SimpleFeatureIterator
  • SimpleFeatureSource
  • Coordinate
  • Polygon
  • GeometryCollection
  • ReferencedEnvelope
origin: osmandapp/Osmand

/**
 * JTS 1.14 does not support intersection on a {@link GeometryCollection}. This function works around this
 * by performing intersection on a flat list of geometry. The resulting list is pre-filtered for invalid
 * or empty geometry (outside of bounds). Invalid geometry are logged as errors.
 *
 * @param envelope non-list geometry defines bounding area
 * @param dataGeoms geometry pre-passed through {@link #flatFeatureList(Geometry)}
 * @return list of geometry from {@code data} intersecting with {@code envelope}.
 */
private static List<Geometry> flatIntersection(Geometry envelope, List<Geometry> dataGeoms) {
  final List<Geometry> intersectedGeoms = new ArrayList<>(dataGeoms.size());
  Geometry nextIntersected;
  for(Geometry nextGeom : dataGeoms) {
    try {
      // AABB intersection culling
      if(envelope.getEnvelopeInternal().intersects(nextGeom.getEnvelopeInternal())) {
        nextIntersected = envelope.intersection(nextGeom);
        if(!nextIntersected.isEmpty()) {
          nextIntersected.setUserData(nextGeom.getUserData());
          intersectedGeoms.add(nextIntersected);
        }
      }
    } catch (TopologyException e) {
      //LoggerFactory.getLogger(JtsAdapter.class).error(e.getMessage(), e);
    }
  }
  return intersectedGeoms;
}
origin: opentripplanner/OpenTripPlanner

GeometryFactory gf = new GeometryFactory();
Coordinate dropPoint = new Coordinate(lon, lat);
pathToStreetCoords[0] = dropPoint;
pathToStreetCoords[1] = origin.getCoordinate();
LineString pathToStreet = gf.createLineString(pathToStreetCoords);
      coords = circleShape.getCoordinates();
    geometryJSON.write(gf.createMultiPoint(coords), sw);
    LOG.debug("done");
  } else if (output.equals(SIsochrone.RESULT_TYPE_SHED)) {
        outputHull = hull.getConcaveHull();
      } catch (Exception e) {
        outputHull = gc.convexHull();
        LOG.debug("Could not generate ConcaveHull for WalkShed, using ConvexHull instead.");
origin: opentripplanner/OpenTripPlanner

public void setGeom(Geometry geom) throws EmptyPolygonException, UnsupportedGeometryException {
  if (geom instanceof MultiPolygon) {
    if (geom.isEmpty()) {
      throw new EmptyPolygonException();
    }
    if (geom.getNumGeometries() > 1) {
      // LOG.warn("Multiple polygons in MultiPolygon, using only the first.");
      // TODO percolate this warning up somehow
    }
    this.geom = geom.getGeometryN(0);
  } else if( geom instanceof Point || geom instanceof Polygon){
    this.geom = geom;
  } else {
    throw new UnsupportedGeometryException( "Non-point, non-polygon Geometry, not supported." );
  }
  // cache a representative point
  Point point = geom.getCentroid();
  this.lat = point.getY();
  this.lon = point.getX();
}
origin: osmandapp/Osmand

private static FeatureStats pointStats(Geometry geom) {
  final FeatureStats featureStats = new FeatureStats();
  final HashSet<Point> pointSet = new HashSet<>(geom.getNumPoints());
  featureStats.totalPts = geom.getNumPoints();
  for(int i = 0; i < geom.getNumGeometries(); ++i) {
    final Point p = (Point) geom.getGeometryN(i);
    featureStats.repeatedPts += pointSet.add(p) ? 0 : 1;
  }
  return featureStats;
}
origin: opentripplanner/OpenTripPlanner

private Geometry removeDuplicatePoints(Geometry routeGeometry) {
  List<Coordinate> coords = new ArrayList<Coordinate>();
  Coordinate last = null;
  for (Coordinate c : routeGeometry.getCoordinates()) {
    if (!c.equals(last)) {
      last = c;
      coords.add(c);
    }
  }
  if (coords.size() < 2) {
    return null;
  }
  Coordinate[] coordArray = new Coordinate[coords.size()];
  return routeGeometry.getFactory().createLineString(coords.toArray(coordArray));
}
origin: mapplus/spatial_statistics_for_geotools_udig

  public List<Coordinate> getCoordinateList(SimpleFeatureCollection inputFeatures) {
    List<Coordinate> pointList = new ArrayList<Coordinate>();

    SimpleFeatureIterator featureIter = inputFeatures.features();
    try {
      while (featureIter.hasNext()) {
        SimpleFeature feature = featureIter.next();
        Geometry geometry = (Geometry) feature.getDefaultGeometry();
        pointList.add(geometry.getCentroid().getCoordinate());
      }
    } finally {
      featureIter.close();
    }

    return pointList;
  }
}
origin: org.geoserver/gwc

/**
 * Computes and returns the area of validity for the given CoordinateReferenceSystem.
 * <p>
 * This method returns the prescribed area of validity for the CRS as computed by
 * {@link CRS#getEnvelope(CoordinateReferenceSystem)} with the exception that the following
 * {@code EPSG:900913} compatible CRS's return the GeoWebCache prescribed bounds so that they
 * align with Google Map tiles: {@code EPSG:900913, EPSG:3857, EPSG:3785}.
 * </p>
 * 
 * @param coordSys
 *            the CRS to compute the area of validity for
 * @return the aov for the CRS, or {@code null} if the CRS does not provide such information
 *         (with the exception of EPSG:900913, see above).
 */
public ReferencedEnvelope getAreaOfValidity(final CoordinateReferenceSystem coordSys) {
  Geometry aovGeom = getAreaOfValidityAsGeometry(coordSys, gridSetBroker);
  if (aovGeom == null) {
    return null;
  }
  Envelope envelope = aovGeom.getEnvelopeInternal();
  double x1 = envelope.getMinX();
  double x2 = envelope.getMaxX();
  double y1 = envelope.getMinY();
  double y2 = envelope.getMaxY();
  ReferencedEnvelope aov = new ReferencedEnvelope(coordSys);
  aov.init(x1, x2, y1, y2);
  return aov;
}
origin: matsim-org/matsim

@Test
public void testShapeFileWriter() throws IOException{
  
  String inFile = "src/test/resources/" + utils.getInputDirectory() + "test.shp";
  
  String outFile = utils.getOutputDirectory() + "/test.shp"; 
  SimpleFeatureSource s = ShapeFileReader.readDataFile(inFile);
    SimpleFeatureCollection fts = s.getFeatures();
    SimpleFeatureIterator it = fts.features();
    SimpleFeature ft = it.next();
    Geometry g = (Geometry) ft.getDefaultGeometry();
    List<SimpleFeature> fc = new ArrayList<>();
    fc.add(ft);
    ShapeFileWriter.writeGeometries(fc, outFile);
    
    SimpleFeatureSource s1 = ShapeFileReader.readDataFile(outFile);
    SimpleFeatureCollection fts1 = s1.getFeatures();
    SimpleFeatureIterator it1 = fts1.features();
    SimpleFeature ft1 = it1.next();
    Geometry g1 = (Geometry) ft1.getDefaultGeometry();
    
    Assert.assertEquals(g.getCoordinates().length, g1.getCoordinates().length);
    
}

origin: matsim-org/matsim

SimpleFeatureType ft = b.buildFeatureType();
GeometryFactory geofac = new GeometryFactory();
LinearRing lr = geofac.createLinearRing(new Coordinate[]{new Coordinate(0,0),new Coordinate(0,1),new Coordinate(1,1),new Coordinate(0,0)});
Polygon p = geofac.createPolygon(lr,null);
MultiPolygon mp = geofac.createMultiPolygon(new Polygon[]{p});		
Collection<SimpleFeature> features = new ArrayList<SimpleFeature>();
Geometry g0 = (Geometry) features.iterator().next().getDefaultGeometry();
SimpleFeatureCollection fts1 = s1.getFeatures();
SimpleFeatureIterator it1 = fts1.features();
SimpleFeature ft1 = it1.next();
Geometry g1 = (Geometry) ft1.getDefaultGeometry();
Assert.assertEquals(g0.getCoordinates().length, g1.getCoordinates().length);
origin: DataSystemsLab/GeoSpark

  public Polygon call(T spatialObject)
  {
    Double x1, x2, y1, y2;
    LinearRing linear;
    Coordinate[] coordinates = new Coordinate[5];
    GeometryFactory fact = new GeometryFactory();
    final Envelope envelope = spatialObject.getEnvelopeInternal();
    x1 = envelope.getMinX();
    x2 = envelope.getMaxX();
    y1 = envelope.getMinY();
    y2 = envelope.getMaxY();
    coordinates[0] = new Coordinate(x1, y1);
    coordinates[1] = new Coordinate(x1, y2);
    coordinates[2] = new Coordinate(x2, y2);
    coordinates[3] = new Coordinate(x2, y1);
    coordinates[4] = coordinates[0];
    linear = fact.createLinearRing(coordinates);
    Polygon polygonObject = new Polygon(linear, null, fact);
    return polygonObject;
  }
});
origin: mapplus/spatial_statistics_for_geotools_udig

private void buildSpatialIndex(SimpleFeatureCollection features) {
  spatialIndex = new STRtree();
  SimpleFeatureIterator featureIter = features.features();
  try {
    while (featureIter.hasNext()) {
      SimpleFeature feature = featureIter.next();
      Geometry geometry = (Geometry) feature.getDefaultGeometry();
      NeighborFeature nearFeature = new NeighborFeature(geometry, feature.getID());
      spatialIndex.insert(geometry.getEnvelopeInternal(), nearFeature);
    }
  } finally {
    featureIter.close();
  }
}
origin: org.geoserver/wms

  /**
   * DOCUMENT ME!
   *
   * @param featureWriter DOCUMENT ME!
   * @param ft DOCUMENT ME!
   *
   * @throws IOException DOCUMENT ME!
   */
  public void startFeature(SVGFeatureWriter featureWriter, SimpleFeature ft)
    throws IOException {
    handler.startFeature(featureWriter, ft);
    Geometry geom = (Geometry) ft.getDefaultGeometry();
    Envelope env = geom.getEnvelopeInternal();
    write(" bounds=\"");
    write(env.getMinX());
    write(' ');
    write(env.getMinY());
    write(' ');
    write(env.getMaxX());
    write(' ');
    write(env.getMaxY());
    write('\"');
  }
}
origin: com.vividsolutions/jts

protected LineString horizontalBisector(Geometry geometry) {
 Envelope envelope = geometry.getEnvelopeInternal();
 // Assert: for areas, minx <> maxx
 double avgY = avg(envelope.getMinY(), envelope.getMaxY());
 return factory.createLineString(new Coordinate[] {
     new Coordinate(envelope.getMinX(), avgY),
     new Coordinate(envelope.getMaxX(), avgY)
   });
}
origin: opentripplanner/OpenTripPlanner

GeometryFactory geomFactory = new GeometryFactory();
    Coordinate[] coordinates = new Coordinate[] { edge.getFromVertex().getCoordinate(),
        edge.getToVertex().getCoordinate() };
    edgeGeom = GeometryUtils.getGeometryFactory().createLineString(coordinates);
    hasGeom = false;
  OffsetCurveBuilder offsetBuilder = new OffsetCurveBuilder(new PrecisionModel(),
      bufParams);
  Coordinate[] coords = offsetBuilder.getOffsetCurve(midLineGeom.getCoordinates(),
      lineWidth * 0.4);
  if (coords.length < 2)
    continue; // Can happen for very small edges (<1mm)
  LineString offsetLine = geomFactory.createLineString(coords);
  Shape midLineShape = shapeWriter.toShape(midLineGeom);
  Shape offsetShape = shapeWriter.toShape(offsetLine);
  vvAttrs.color = null;
  vvAttrs.label = null;
  Point point = geomFactory.createPoint(new Coordinate(vertex.getLon(), vertex.getLat()));
  boolean render = evRenderer.renderVertex(vertex, vvAttrs);
  if (!render)
  context.graphics.draw(shape);
  if (vvAttrs.label != null && lineWidth > 6.0f
      && context.bbox.contains(point.getCoordinate())) {
    context.graphics.setColor(Color.BLACK);
    int labelWidth = largeFontMetrics.stringWidth(vvAttrs.label);
origin: org.geotools/gt-main

SimpleFeatureIterator r = features();
try {
  Envelope newBBox = new Envelope();
  Envelope internal;
  SimpleFeature feature;
  while (r.hasNext()) {
    feature = r.next();
    final Geometry geom = ((Geometry)feature.getDefaultGeometry());
    if(geom != null) {
      internal = geom.getEnvelopeInternal();
      newBBox.expandToInclude(internal);
  return new ReferencedEnvelope(newBBox, target);
} catch (Exception e) {
  throw new RuntimeException(
      "Exception occurred while computing reprojected bounds", e);
} finally {
  r.close();
origin: org.geotools/gt-render

public IndexedFeatureResults(SimpleFeatureCollection results) throws IOException,
    IllegalAttributeException {
  // copy results attributes
  super(null,results.getSchema());
  
      
  // load features into the index
  SimpleFeatureIterator reader = null;
  bounds = new Envelope();
  count = 0;
  try {
    reader = results.features();
    SimpleFeature f;
    Envelope env;
    while (reader.hasNext()) {
      f = reader.next();
      env = ((Geometry) f.getDefaultGeometry()).getEnvelopeInternal();
      bounds.expandToInclude(env);
      count++;
      index.insert(env, f);
    }
  } finally {
    if(reader != null)
      reader.close();
  }
}
origin: com.eventsourcing/h2

/**
 * Get the union.
 *
 * @param r the other geometry
 * @return the union of this geometry envelope and another geometry envelope
 */
public Value getEnvelopeUnion(ValueGeometry r) {
  GeometryFactory gf = new GeometryFactory();
  Envelope mergedEnvelope = new Envelope(getGeometryNoCopy().getEnvelopeInternal());
  mergedEnvelope.expandToInclude(r.getGeometryNoCopy().getEnvelopeInternal());
  return get(gf.toGeometry(mergedEnvelope));
}
origin: com.vividsolutions/jts

  private static Geometry clipGeometryCollection(Geometry geom, Envelope clipEnv)
  {
    Geometry clipPoly = geom.getFactory().toGeometry(clipEnv);
    List clipped = new ArrayList();
    for (int i = 0; i < geom.getNumGeometries(); i++) {
      Geometry g = geom.getGeometryN(i);
      Geometry result = null;
      // don't clip unless necessary
      if (clipEnv.contains(g.getEnvelopeInternal()))
          result = g;
      else if (clipEnv.intersects(g.getEnvelopeInternal())) {
        result = clipPoly.intersection(g);
        // keep vertex key info
        result.setUserData(g.getUserData());
      }

      if (result != null && ! result.isEmpty()) {
        clipped.add(result);
      }
    }
    return geom.getFactory().createGeometryCollection(GeometryFactory.toGeometryArray(clipped));
  }
}
origin: bedatadriven/activityinfo

GeometryType geometryType = (GeometryType) featureSource.getSchema().getDescriptor(sourceIndex).getType();
GeometryConverter converter = new GeometryConverter(geometryType);
SimpleFeatureIterator it = featureSource.getFeatures().features();
while(it.hasNext()) {
  SimpleFeature feature = it.next();
  ResourceId sourceId = ResourceId.valueOf(feature.getID());
  ResourceId targetId = idMap.get(sourceId);
    Geometry geometry = converter.toWgs84(feature.getAttribute(sourceIndex));
    System.out.print("Updating geometry for " + targetId + " [" + geometry.getGeometryType() + "] ... ");
origin: eu.agrosense.server/observations

Geometry intersection = cropToGeometry.intersection(meg0.getBoundingBox());
ReferencedEnvelope bb0 = StandardSizeGrid.makeBoundingBox(meg0.getBoundingBox().getEnvelopeInternal(), cellSize);
ReferencedEnvelope bb1 = StandardSizeGrid.makeBoundingBox(intersection.getEnvelopeInternal(), cellSize);
assert bb0.covers(bb1);
Point offset = cellSize.getCell(bb0, new Coordinate(bb1.getMinX(), bb1.getMaxY()));
Dimension dim0 = cellSize.getDimension(bb0);
Dimension dim1 = cellSize.getDimension(bb1);
    .setValue(String.valueOf(dim1.height));
meg1PM.getAt(MeasurementGrid.PROP_BOUNDING_BOX)
    .setValue(JTS.toGeometry(bb1).toText());
meg1PM.getAt(MeasurementGrid.PROP_MEASUREMENTS)
    .setValue(new MeasurementsConverter().toString(val1));
obs1Envelope.expandToInclude(bb1);
com.vividsolutions.jts.geomGeometry

Javadoc

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 will use a canonical form for Geometrys returned from spatial analysis 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.

Most used methods

  • getEnvelopeInternal
    Gets an Envelope containing the minimum and maximum x and y values in this Geometry. If the geometr
  • getCoordinates
    Returns an array containing the values of all the vertices for this geometry. If the geometry is a c
  • isEmpty
    Tests whether the set of points covered by this Geometry is empty.
  • getCentroid
    Computes the centroid of this Geometry. The centroid is equal to the centroid of the set of componen
  • getGeometryN
    Returns an element Geometry from a GeometryCollection(or this, if the geometry is not a collection).
  • toText
    Returns the Well-known Text representation of this Geometry. For a definition of the Well-known Text
  • getNumGeometries
    Returns the number of Geometrys in a GeometryCollection(or 1, if the geometry is not a collection).
  • getFactory
    Gets the factory which contains the context in which this geometry was created.
  • getGeometryType
    Returns the name of this Geometry's actual class.
  • getSRID
    Returns the ID of the Spatial Reference System used by the Geometry. JTS supports Spatial Reference
  • getCoordinate
    Returns a vertex of this Geometry (usually, but not necessarily, the first one). The returned coordi
  • intersection
    Computes a Geometry representing the point-set which is common to both this Geometry and the other
  • getCoordinate,
  • intersection,
  • buffer,
  • contains,
  • getArea,
  • getEnvelope,
  • intersects,
  • union,
  • apply,
  • getLength

Popular in Java

  • Parsing JSON documents to java classes using gson
  • findViewById (Activity)
  • requestLocationUpdates (LocationManager)
  • getResourceAsStream (ClassLoader)
  • OutputStream (java.io)
    A writable sink for bytes.Most clients will use output streams that write data to the file system (
  • MalformedURLException (java.net)
    This exception is thrown when a program attempts to create an URL from an incorrect specification.
  • DateFormat (java.text)
    Formats or parses dates and times.This class provides factories for obtaining instances configured f
  • Reference (javax.naming)
  • JOptionPane (javax.swing)
  • Reflections (org.reflections)
    Reflections one-stop-shop objectReflections scans your classpath, indexes the metadata, allows you t
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now