Java Code Examples for com.vividsolutions.jts.geom.Geometry#isEmpty()

The following examples show how to use com.vividsolutions.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: GeometryUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static Geometry cleanGeometry(final Geometry g) {
	//follow the proposition of https://locationtech.github.io/jts/jts-faq.html#G1
	if (g == null || g.isEmpty()) return g; 
	Geometry g2 = g.buffer(0.0, BufferParameters.DEFAULT_QUADRANT_SEGMENTS,
			BufferParameters.CAP_FLAT);
	if (g2.isEmpty()) {
		if (g instanceof Polygon) {
			Polygon p = (Polygon) g;
			Geometry g3 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getExteriorRing().getCoordinates());
			for (int i = 0; i < p.getNumInteriorRing(); i++) {
				Geometry g4 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getInteriorRingN(i).getCoordinates());
				g3 = g3.difference(g4);
			}
			return g3;
		}else {
			return GeometryUtils.GEOMETRY_FACTORY.createGeometry(g);
		}
	}
	return g2;
}
 
Example 2
Source File: Distance3DOp.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void computeMinDistanceMultiMulti(Geometry g0, Geometry g1, boolean flip) {
	if (g0 instanceof GeometryCollection) {
		int n = g0.getNumGeometries();
		for (int i = 0; i < n; i++) {
			Geometry g = g0.getGeometryN(i);
			computeMinDistanceMultiMulti(g, g1, flip);
			if (isDone)	return;
		}
	}
	else {
		// handle case of multigeom component being empty
		if (g0.isEmpty())
			return;
		
		// compute planar polygon only once for efficiency
		if (g0 instanceof Polygon) {
			computeMinDistanceOneMulti(polyPlane(g0), g1, flip);
		}
		else 
			computeMinDistanceOneMulti(g0, g1, flip);
	}
}
 
Example 3
Source File: BufferResultMatcher.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean isBufferResultMatch(Geometry actualBuffer, Geometry expectedBuffer, double distance)
{
	if (actualBuffer.isEmpty() && expectedBuffer.isEmpty())
		return true;
	
	/**
	 * MD - need some more checks here - symDiffArea won't catch very small holes ("tears") 
	 * near the edge of computed buffers (which can happen in current version of JTS (1.8)).  
	 * This can probably be handled by testing
	 * that every point of the actual buffer is at least a certain distance away from the 
	 * geometry boundary.  
	*/
	if (! isSymDiffAreaInTolerance(actualBuffer, expectedBuffer))
		return false;
	
	if (! isBoundaryHausdorffDistanceInTolerance(actualBuffer, expectedBuffer, distance))
		return false;
	
	return true;
}
 
Example 4
Source File: GeometryTreeModel.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String geometryText(Geometry geom, int size, String tag)
{
  StringBuilder buf = new StringBuilder();
  if (tag != null && tag.length() > 0) {
    buf.append(tag + " : ");
  }
  buf.append(geom.getGeometryType());
  if (geom.isEmpty()) {
    buf.append(" EMPTY");
  }
  else {
    if (size > 0) {
      buf.append(" " + sizeString(size));
    }
  }
  
  if (hasLength(geom)) {
  	buf.append("   --     Len: " + geom.getLength());
  }
  if (hasArea(geom)) { 
    buf.append("      Area: " + area(geom));
  }
  
  return buf.toString();
}
 
Example 5
Source File: ProcessingUtils.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Check GML Footprint validity
 */
public static boolean checkGMLFootprint (String footprint)
{
   try
   {
      Configuration configuration = new GMLConfiguration ();
      Parser parser = new Parser (configuration);

      Geometry geom =
            (Geometry) parser.parse (new InputSource (
                  new StringReader (footprint)));
      if (!geom.isEmpty() && !geom.isValid())
      {
         LOGGER.error("Wrong footprint");
         return false;
      }
   }
   catch (Exception e)
   {
      LOGGER.error("Error in extracted footprint: " + e.getMessage());
      return false;
   }
   return true;
}
 
Example 6
Source File: GamaShape.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setInnerGeometry(final Geometry geom) {
	if (geom == null) {
		geometry = null;
		return;
	}
	if (geom.isEmpty()) {
		// See Issue 725
		return;
	}
	if (geom instanceof GeometryCollection && geom.getNumGeometries() == 1) {
		geometry = geom.getGeometryN(0);
	} else {
		geometry = geom;
	}
}
 
Example 7
Source File: GamaGeoJsonFile.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public void readShapes(final IScope scope) {
	final IList<IShape> list = getBuffer();
	int size = 0;
	final SimpleFeatureCollection fc = getFeatureCollection(scope);
	if (fc == null) { return; }
	final Envelope3D env = Envelope3D.of(fc.getBounds());
	size = fc.size();
	int index = 0;
	computeProjection(scope, env);
	try (SimpleFeatureIterator reader = fc.features()) {
		while (reader.hasNext()) {
			index++;
			if (index % 20 == 0) {
				scope.getGui().getStatus(scope).setSubStatusCompletion(index / (double) size);
			}
			final SimpleFeature feature = reader.next();
			Geometry g = (Geometry) feature.getDefaultGeometry();
			if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) {
				g = gis.transform(g);
				if (!with3D) {
					g.apply(ZERO_Z);
					g.geometryChanged();
				}
				list.add(new GamaGisGeometry(g, feature));
			} else if (g == null) {
				// See Issue 725
				GAMA.reportError(scope,
						GamaRuntimeException
								.warning("GamaGeoJsonFile.fillBuffer; geometry could not be added  as it is "
										+ "nil: " + feature.getIdentifier(), scope),
						false);
			}
		}
	}
	if (size > list.size()) {
		GAMA.reportError(scope, GamaRuntimeException.warning("Problem with file " + getFile(scope) + ": only "
				+ list.size() + " of the " + size + " geometries could be added", scope), false);
	}
}
 
Example 8
Source File: GamaSqlConnection.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private void readTable(final IScope scope, final String tableName, final String filterStr) {

		final IList list = getBuffer();
		final QueryInfo queryInfo = new QueryInfo(scope, this.dataStore, tableName, filterStr);
		try (SimpleFeatureIterator reader = queryInfo.getRecordSet().features()) {

			final int size = queryInfo.getSize();
			final Envelope3D env = queryInfo.getEnvelope();
			int index = 0;
			computeProjection(scope, env); // ??
			// reader = store.getFeatureReader();
			// final int i = 0;
			while (reader.hasNext()) {
				scope.getGui().getStatus(scope).setSubStatusCompletion(index++ / (double) size);
				final Feature feature = reader.next();

				// DEBUG.LOG("Record " + i++ + ": " +
				// feature.getValue().toString());

				Geometry g = (Geometry) feature.getDefaultGeometryProperty().getValue();
				if (g != null && !g.isEmpty()) {
					g = gis.transform(g);
					list.add(new GamaGisGeometry(g, feature));
				} else {
					GAMA.reportError(scope, GamaRuntimeException.warning(
							"GamaSqlConnection.fillBuffer; geometry could not be added : " + feature.getIdentifier(),
							scope), false);
				}
			}
		} catch (final Exception e) {
			throw GamaRuntimeException.create(e, scope);
		} finally {
			scope.getGui().getStatus(scope).endSubStatus("Reading table " + tableName);
		}
	}
 
Example 9
Source File: GeoWaveGeoIndexer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static SimpleFeature createFeature(final SimpleFeatureType featureType, final Statement statement) throws ParseException {
    final String subject = StatementSerializer.writeSubject(statement);
    final String predicate = StatementSerializer.writePredicate(statement);
    final String object = StatementSerializer.writeObject(statement);
    final String context = StatementSerializer.writeContext(statement);

    // create the feature
    final Object[] noValues = {};

    // create the hash
    final String statementId = Md5Hash.md5Base64(StatementSerializer.writeStatement(statement));
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(featureType, noValues, statementId);

    // write the statement data to the fields
    final Geometry geom = GeoParseUtils.getGeometry(statement, new GmlParser());
    if(geom == null || geom.isEmpty() || !geom.isValid()) {
        throw new ParseException("Could not create geometry for statement " + statement);
    }
    newFeature.setDefaultGeometry(geom);

    newFeature.setAttribute(SUBJECT_ATTRIBUTE, subject);
    newFeature.setAttribute(PREDICATE_ATTRIBUTE, predicate);
    newFeature.setAttribute(OBJECT_ATTRIBUTE, object);
    newFeature.setAttribute(CONTEXT_ATTRIBUTE, context);
    // GeoWave does not support querying based on a user generated feature ID
    // So, we create a separate ID attribute that it can query on.
    newFeature.setAttribute(GEO_ID_ATTRIBUTE, statementId);

    // preserve the ID that we created for this feature
    // (set the hint to FALSE to have GeoTools generate IDs)
    newFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

    return newFeature;
}
 
Example 10
Source File: GeoMesaGeoIndexer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static SimpleFeature createFeature(final SimpleFeatureType featureType, final Statement statement) throws ParseException {
    final String subject = StatementSerializer.writeSubject(statement);
    final String predicate = StatementSerializer.writePredicate(statement);
    final String object = StatementSerializer.writeObject(statement);
    final String context = StatementSerializer.writeContext(statement);

    // create the feature
    final Object[] noValues = {};

    // create the hash
    final String statementId = Md5Hash.md5Base64(StatementSerializer.writeStatement(statement));
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(featureType, noValues, statementId);

    // write the statement data to the fields
    final Geometry geom = GeoParseUtils.getGeometry(statement, new GmlParser());
    if(geom == null || geom.isEmpty() || !geom.isValid()) {
        throw new ParseException("Could not create geometry for statement " + statement);
    }
    newFeature.setDefaultGeometry(geom);

    newFeature.setAttribute(SUBJECT_ATTRIBUTE, subject);
    newFeature.setAttribute(PREDICATE_ATTRIBUTE, predicate);
    newFeature.setAttribute(OBJECT_ATTRIBUTE, object);
    newFeature.setAttribute(CONTEXT_ATTRIBUTE, context);

    // preserve the ID that we created for this feature
    // (set the hint to FALSE to have GeoTools generate IDs)
    newFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

    return newFeature;
}
 
Example 11
Source File: JTSTestBuilderFrame.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Coordinate pickOffset(Geometry a, Geometry b) {
  if (a != null && ! a.isEmpty()) {
    return a.getCoordinates()[0];
  }
  if (b != null && ! b.isEmpty()) {
    return b.getCoordinates()[0];
  }
  return null;
}
 
Example 12
Source File: GeometryTreeModel.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public GeometryNode(Geometry geom, int size, String tag, GeometryContext context)
{
  super(geometryText(geom, size, tag));
  this.context = context;
  if (geom.isEmpty()) {
    isLeaf = true;
  }
}
 
Example 13
Source File: LineNoder.java    From geowe-core with GNU General Public License v3.0 5 votes vote down vote up
public Geometry extractPoint(final Collection<Geometry> lines) {
	Geometry point = null;
	for (final Iterator<Geometry> i = lines.iterator(); i.hasNext();) {
		final Geometry geometry = i.next();
		if (!geometry.isEmpty()) {
			point = geometry.getFactory().createPoint(geometry.getCoordinate());
		}
	}
	return point;
}
 
Example 14
Source File: GeometryUtils.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public static GamaPoint getFirstPointOf(final IShape shape) {
	final Geometry g = shape.getInnerGeometry();
	if (g.isEmpty()) { return null; }
	return (GamaPoint) g.getCoordinates()[0];
}
 
Example 15
Source File: GeometryUtils.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public static GamaPoint getLastPointOf(final IShape shape) {
	final Geometry g = shape.getInnerGeometry();
	if (g.isEmpty()) { return null; }
	final Coordinate[] cc = g.getCoordinates();
	return (GamaPoint) cc[cc.length - 1];
}
 
Example 16
Source File: GamaShapeFile.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
protected void readShapes(final IScope scope) {
	scope.getGui().getStatus(scope).beginSubStatus("Reading file " + getName(scope));
	ShapefileDataStore store = null;
	final File file = getFile(scope);
	final IList list = getBuffer();
	int size = 0;
	try {
		store = getDataStore(file.toURI().toURL());
		final ContentFeatureSource source = store.getFeatureSource();
		final Envelope3D env = Envelope3D.of(source.getBounds());
		size = source.getCount(Query.ALL);
		int index = 0;
		computeProjection(scope, env);
		try (FeatureReader reader = store.getFeatureReader()) {
			while (reader.hasNext()) {
				index++;
				if (index % 20 == 0) {
					scope.getGui().getStatus(scope).setSubStatusCompletion(index / (double) size);
				}
				final Feature feature = reader.next();
				Geometry g = (Geometry) feature.getDefaultGeometryProperty().getValue();
				if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) {
					if (!with3D && !g.isValid()) {
						g = GeometryUtils.cleanGeometry(g);
					}
					g = gis.transform(g);
					if (!with3D) {
						g.apply(ZERO_Z);
						g.geometryChanged();
					}
					g = multiPolygonManagement(g);
					GamaGisGeometry gt = new GamaGisGeometry(g, feature);
					if (gt.getInnerGeometry() != null)
						list.add(gt);
					
				} else if (g == null) {
					// See Issue 725
					GAMA.reportError(scope,
							GamaRuntimeException
									.warning("GamaShapeFile.fillBuffer; geometry could not be added  as it is "
											+ "nil: " + feature.getIdentifier(), scope),
							false);
				}
			}
		}
	} catch (final IOException e) {
		throw GamaRuntimeException.create(e, scope);
	} finally {
		if (store != null) {
			store.dispose();
		}
		scope.getGui().getStatus(scope).endSubStatus("Reading file " + getName(scope));
	}
	if (size > list.size()) {
		GAMA.reportError(scope, GamaRuntimeException.warning("Problem with file " + getFile(scope) + ": only "
				+ list.size() + " of the " + size + " geometries could be added", scope), false);
	}
}
 
Example 17
Source File: GeometryValidator.java    From geowe-core with GNU General Public License v3.0 4 votes vote down vote up
private void validate(final Geometry geom, final List<ValidationResult> validationErrors) {
	
	if (geom.isEmpty()) {
		return;
	}

	if (geom instanceof GeometryCollection) {
		final GeometryCollection gc = (GeometryCollection) geom;
		for (int numGeom = 0; numGeom < gc.getNumGeometries(); numGeom++) {
			validate(gc.getGeometryN(numGeom), validationErrors);
		}
	}

	final ValidationResult result = new ValidationResult();
	result.setWkt(geom.toText());
	final List<String> messages = new ArrayList<String>();
	
	if (!geom.isValid()) {
		messages.add("Error en topología básica");
	}

	if (!geom.isSimple()) {
		messages.add("No es una geometría simple");
	}

	if (repeatedPointTester.hasRepeatedPoint(geom)) {
		messages.add("Se encuentran vértices repetidos");
	}

	if (geom instanceof Polygon) {
		final Polygon polygon = (Polygon) geom;
		if (CGAlgorithms.isCCW(polygon.getExteriorRing().getCoordinates())) {
			messages.add("Error en orientación del polígono");
		} else {

			for (int numRing = 0; numRing < polygon.getNumInteriorRing(); numRing++) {
				if (!CGAlgorithms.isCCW(polygon.getInteriorRingN(numRing).getCoordinates())) {
					messages.add("Error en orientación del polígono en anillos interiores");
					break;
				}
			}
		}

		if (!validateMinPolygonArea(geom)) {
			messages.add("Error en validación mínima de area de un polígono");
		}
	}

	if (!validateMinSegmentLength(geom)) {
		messages.add("Error en validación mínima de longitud de segmento. Coordenadas");
		result.setErrorsPoints(errorCoordinates);
	}


	if(!messages.isEmpty()) {
		result.setMessages(messages);
		validationErrors.add(result);
	}		
}