com.vividsolutions.jts.geom.Geometry Java Examples

The following examples show how to use com.vividsolutions.jts.geom.Geometry. 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 Project: gama   Author: gama-platform   File: GamaGisFile.java    License: GNU General Public License v3.0 7 votes vote down vote up
protected Geometry multiPolygonManagement(final Geometry geom) {
	if (geom instanceof MultiPolygon) {
		final Polygon gs[] = new Polygon[geom.getNumGeometries()];
		for (int i = 0; i < geom.getNumGeometries(); i++) {
			final Polygon p = (Polygon) geom.getGeometryN(i);
			final ICoordinates coords = GeometryUtils.getContourCoordinates(p);
			final LinearRing lr = GEOMETRY_FACTORY.createLinearRing(coords.toCoordinateArray());
			try (final Collector.AsList<LinearRing> holes = Collector.getList()) {
				for (int j = 0; j < p.getNumInteriorRing(); j++) {
					final LinearRing h = (LinearRing) p.getInteriorRingN(j);
					if (!hasNullElements(h.getCoordinates())) {
						holes.add(h);
					}
				}
				LinearRing[] stockArr = new LinearRing[holes.size()];
				stockArr = holes.items().toArray(stockArr);
				gs[i] = GEOMETRY_FACTORY.createPolygon(lr, stockArr);
			}
		}
		return GEOMETRY_FACTORY.createMultiPolygon(gs);
	}
	return geom;
}
 
Example #2
Source Project: geowe-core   Author: geowe   File: DivideLineStringTool.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Collection<Geometry> getLines(final Geometry geom) {
	final List<Geometry> linesList = new ArrayList<Geometry>();
	final LinearComponentExtracter lineFilter = new LinearComponentExtracter(
			linesList);

	geom.apply(lineFilter);

	return linesList;
}
 
Example #3
Source Project: geomajas-project-server   Author: geomajas   File: BeanFeatureModel.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public Geometry getGeometry(Object feature) throws LayerException {
	Entity entity = entityMapper.asEntity(feature);
	Object geometry = entity.getAttribute(getGeometryAttributeName());
	if (!wkt || null == geometry) {
		log.debug("bean.getGeometry {}", geometry);
		return (Geometry) geometry;
	} else {
		try {
			WKTReader reader = new WKTReader(new GeometryFactory(new PrecisionModel(), srid));
			Geometry geom = reader.read((String) geometry);
			log.debug("bean.getGeometry {}", geom);
			return geom;
		} catch (Throwable t) {
			throw new LayerException(t, ExceptionCode.FEATURE_MODEL_PROBLEM, geometry);
		}
	}
}
 
Example #4
Source Project: rya   Author: apache   File: GeoTemporalMongoDBStorageStrategy.java    License: Apache License 2.0 6 votes vote down vote up
private Document[] getGeoObjs(final Collection<IndexingExpr> geoFilters) {
    final List<Document> objs = new ArrayList<>();
    geoFilters.forEach(filter -> {
        final GeoPolicy policy = GeoPolicy.fromURI(filter.getFunction());
        final WKTReader reader = new WKTReader();
        final String geoStr = ((Value) filter.getArguments()[0]).stringValue();
        try {
            //This method is what is used in the GeoIndexer.
            final Geometry geo = reader.read(geoStr);
            objs.add(getGeoObject(geo, policy));
        } catch (final GeoTemporalIndexException | UnsupportedOperationException | ParseException e) {
            LOG.error("Unable to parse '" + geoStr + "'.", e);
        }
    });
    return objs.toArray(new Document[]{});
}
 
Example #5
Source Project: jts   Author: metteo   File: JTSTestBuilderFrame.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void copyResultToTest() 
{
  Object currResult = tbModel.getResult();
  if (! (currResult instanceof Geometry))
    return;
  tbModel.addCase(new Geometry[] { (Geometry) currResult, null }, 
  		"Result of " + tbModel.getOpName());
  updateTestCaseView();
  testListPanel.populateList();  
}
 
Example #6
Source Project: jts   Author: metteo   File: MiscellaneousTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testMultiLineStringGetBoundary2() throws Exception {
  Geometry g = reader.read("MULTILINESTRING("
        + "(0 0,  100 0, 50 50),"
        + "(50 50, 50 0))");
  Geometry m = reader.read("MULTIPOINT(0 0, 50 0)");
  assertTrue(m.equalsExact(g.getBoundary()));
}
 
Example #7
Source Project: jts   Author: metteo   File: SpatialIndexFunctions.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Geometry strTreeBounds(Geometry geoms)
{
  STRtree index = buildSTRtree(geoms);
  List bounds = new ArrayList();
  addBounds(index.getRoot(), bounds, geoms.getFactory());
  return geoms.getFactory().buildGeometry(bounds);
}
 
Example #8
Source Project: jts   Author: metteo   File: DistanceTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testEverything() throws Exception {
  Geometry g1 = reader.read("POLYGON ((40 320, 200 380, 320 80, 40 40, 40 320),  (180 280, 80 280, 100 100, 220 140, 180 280))");
  Geometry g2 = reader.read("POLYGON ((160 240, 120 240, 120 160, 160 140, 160 240))");
  assertEquals(18.97366596, g1.distance(g2), 1E-5);

  g2 = reader.read("POLYGON ((160 240, 120 240, 120 160, 180 100, 160 240))");
  assertEquals(0.0, g1.distance(g2), 1E-5);

  LineString l1 = (LineString) reader.read("LINESTRING(10 10, 20 20, 30 40)");
  LineString l2 = (LineString) reader.read("LINESTRING(10 10, 20 20, 30 40)");
  assertEquals(0.0, l1.distance(l2), 1E-5);
}
 
Example #9
Source Project: dhis2-core   Author: dhis2   File: JtsXmlModule.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings({"rawtypes","unchecked"})
public JtsXmlModule( GeometryFactory geometryFactory )
{
    super( "JtsXmlModule", new Version( 1, 0, 0, (String) null, "org.dhis", "dhis-service-node" ) );
    this.addSerializer( Geometry.class, new GeometrySerializer() );
    XmlGenericGeometryParser genericGeometryParser = new XmlGenericGeometryParser( geometryFactory );
    this.addDeserializer( Geometry.class, new GeometryDeserializer( genericGeometryParser ) );
}
 
Example #10
Source Project: jts   Author: metteo   File: BufferResultValidatorTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
void runTest(String wkt, double dist)
throws Exception
{
	Geometry g = rdr.read(wkt);
	Geometry buf = g.buffer(dist);
  BufferResultValidator validator = new BufferResultValidator(g, dist, buf);
  
  if (! validator.isValid()) {
    String msg = validator.getErrorMessage();

    System.out.println(msg);
    System.out.println(WKTWriter.toPoint(validator.getErrorLocation()));
  }
	assertTrue(validator.isValid());
}
 
Example #11
Source Project: jts   Author: metteo   File: NodingFunctions.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Runs a ScaledNoder on input.
 * Input vertices should be rounded to precision model.
 * 
 * @param geom
 * @param scaleFactor
 * @return the noded geometry
 */
public static Geometry scaledNoding(Geometry geom, double scaleFactor)
{
  List segs = createSegmentStrings(geom);
  PrecisionModel fixedPM = new PrecisionModel(scaleFactor);
  Noder noder = new ScaledNoder(new MCIndexSnapRounder(new PrecisionModel(1.0)),
      fixedPM.getScale());
  noder.computeNodes(segs);
  Collection nodedSegStrings = noder.getNodedSubstrings();
  return SegmentStringUtil.toGeometry(nodedSegStrings, FunctionsUtil.getFactoryOrDefault(geom));
}
 
Example #12
Source Project: jts   Author: metteo   File: LineDissolver.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Dissolves the linear components in a geometry.
 * 
 * @param g the geometry to dissolve
 * @return the dissolved lines
 */
public static Geometry dissolve(Geometry g)
{
  LineDissolver d = new LineDissolver();
  d.add(g);
  return d.getResult();
}
 
Example #13
Source Project: rcrs-server   Author: roborescue   File: GMLTraversabilityValidator.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Find the index of the subgeometry the given edge is part of. Return -1 if
 * the edge is not contained in the geometry at all.
 * @param edge
 * @param geom
 * @return
 */
private static int findPolygonPartOfEdge(GMLDirectedEdge edge, Geometry geom) {
    for (int i = 0; i < geom.getNumGeometries(); i++) {
        if (edgePartOfPolygon(edge, geom.getGeometryN(i))) {
            return i;
        }
    }
    return -1;
}
 
Example #14
Source Project: jts   Author: metteo   File: SimpleDemo.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void demonstrateWkb() {
	GeometryFactory gf = new GeometryFactory();

	WKBReader wkbReader = new WKBReader(gf);
	WKBWriter wkbWriter = new WKBWriter();

	// geometry collection from above
	String hexEncodedWkb = "00000000070000000600000000014132D53A3BC2DADC414"
			+ "10BBD1DFB613500000000040000000200000000014132D53A3BC2DADC414"
			+ "10BBD1DFB61350000000001415026FE8EF0B6B74153F78BCEFDB09A00000"
			+ "00002000000024132D53A3BC2DADC41410BBD1DFB6135415026FE8EF0B6B"
			+ "74153F78BCEFDB09A0000000005000000020000000002000000024132D53"
			+ "A3BC2DADC41410BBD1DFB6135415026FE8EF0B6B74153F78BCEFDB09A000"
			+ "0000002000000024132D53A3BC2DADC41410BBD1DFB6135415026FE8EF0B"
			+ "6B74153F78BCEFDB09A000000000300000001000000044132D53A3BC2DAD"
			+ "C41410BBD1DFB6135415026FE8EF0B6B74153F78BCEFDB09A4157C81E8EF"
			+ "0B6B7415F693E8EFDB09A4132D53A3BC2DADC41410BBD1DFB61350000000"
			+ "00600000002000000000300000001000000044132D53A3BC2DADC41410BB"
			+ "D1DFB6135415026FE8EF0B6B74153F78BCEFDB09A4157C81E8EF0B6B7415"
			+ "F693E8EFDB09A4132D53A3BC2DADC41410BBD1DFB6135000000000300000"
			+ "001000000044132D53A3BC2DADC41410BBD1DFB6135415026FE8EF0B6B74"
			+ "153F78BCEFDB09A4157C81E8EF0B6B7415F693E8EFDB09A4132D53A3BC2D"
			+ "ADC41410BBD1DFB6135";

	try {
		Geometry g = wkbReader.read(WKBReader.hexToBytes(hexEncodedWkb));

		sLogger.info("Geom from WKB: " + g);

		byte[] freshWkb = wkbWriter.write(g);
		String freshWkbHex = WKBWriter.toHex(freshWkb);

		sLogger.warning("Hexes are equal?   "
				+ hexEncodedWkb.equals(freshWkbHex));
	} catch (ParseException e) {
		sLogger.log(Level.WARNING, "Unable to parse hex wkb", e);
	}
}
 
Example #15
Source Project: jts   Author: metteo   File: GeometryResult.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean equals(Result other, double tolerance) {
  if (!(other instanceof GeometryResult)) {
    return false;
  }
  GeometryResult otherGeometryResult = (GeometryResult) other;
  Geometry otherGeometry = otherGeometryResult.geometry;

  Geometry thisGeometryClone = geometry.copy();
  Geometry otherGeometryClone = otherGeometry.copy();
  thisGeometryClone.normalize();
  otherGeometryClone.normalize();
  return thisGeometryClone.equalsExact(otherGeometryClone, tolerance);
}
 
Example #16
Source Project: gama   Author: gama-platform   File: ShapeExecuter.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param scope
 * @param shape
 * @return
 */
private Geometry addToroidalParts(final IScope scope, final Geometry shape) {
	Geometry result = shape;
	final ITopology t = scope.getTopology();
	if (t != null && t.isTorus()) {
		final List<Geometry> geoms = t.listToroidalGeometries(shape);
		final Geometry all = GEOMETRY_FACTORY.buildGeometry(geoms);
		final Geometry world = scope.getSimulation().getInnerGeometry();
		result = all.intersection(world);
		// WARNING Does not correctly handle rotations or translations
	}
	return result;
}
 
Example #17
Source Project: fiware-cepheus   Author: Orange-OpenSource   File: Geospatial.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a Polygon at the geotools format
 * @param points points of the Polygon
 * @return a polygon
 */
public static Polygon createPolygon(Geometry[] points) {
    Coordinate[] coordinates = new Coordinate[points.length];
    for (int i = 0; i < points.length; i++) {
        coordinates[i] = points[i].getCoordinate();
    }
    return geometryFactory.createPolygon(coordinates);
}
 
Example #18
Source Project: gama   Author: gama-platform   File: GeometryUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static ICoordinates getContourCoordinates(final Geometry g) {
	if (g instanceof Polygon) { return getContourCoordinates((Polygon) g); }
	if (g instanceof LineString) { return getContourCoordinates((LineString) g); }
	if (g instanceof Point) { return getContourCoordinates((Point) g); }
	if (g instanceof GeometryCollection) { return getContourCoordinates(g.convexHull()); }
	return ICoordinates.EMPTY;
}
 
Example #19
Source Project: jts   Author: metteo   File: GeometryPrecisionReducerTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testTinySquareCollapse()
    throws Exception
{
  Geometry g = reader.read("POLYGON (( 0 0, 0 .4, .4 .4, .4 0, 0 0 ))");
  Geometry g2 = reader.read("POLYGON EMPTY");
  Geometry gReduce = reducer.reduce(g);
  assertEqualsExactAndHasSameFactory(gReduce, g2);
}
 
Example #20
Source Project: jts   Author: metteo   File: GeometryTestCase.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Reads a {@link Geometry} from a WKT string using a custom {@link GeometryFactory}.
 *  
 * @param geomFactory the custom factory to use
 * @param wkt the WKT string
 * @return the geometry read
 */
protected Geometry read(GeometryFactory geomFactory, String wkt) {
  WKTReader reader = new WKTReader(geomFactory);
  try {
     return reader.read(wkt);
  } catch (ParseException e) {
    throw new RuntimeException(e.getMessage());
  }
}
 
Example #21
Source Project: gama   Author: gama-platform   File: GeometryUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static int nbCommonPoints(final Geometry p1, final Geometry p2) {
	try (final ICollector<Coordinate> cp = Collector.getSet()) {
		final List<Coordinate> coords = Arrays.asList(p1.getCoordinates());
		for (final Coordinate pt : p2.getCoordinates()) {
			if (coords.contains(pt)) {
				cp.add(pt);
			}
		}
		return cp.size();
	}
}
 
Example #22
Source Project: jts   Author: metteo   File: GeometryPrecisionReducerTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSquareKeepCollapse()
    throws Exception
{
  Geometry g = reader.read("POLYGON (( 0 0, 0 1.4, .4 .4, .4 0, 0 0 ))");
  Geometry g2 = reader.read("POLYGON EMPTY");
  Geometry gReduce = reducerKeepCollapse.reduce(g);
  assertEqualsExactAndHasSameFactory(gReduce, g2);
}
 
Example #23
Source Project: product-cep   Author: wso2-attic   File: Disruption.java    License: Apache License 2.0 5 votes vote down vote up
public static Geometry createGeometry(String str) {
    GeometryJSON j = new GeometryJSON();
    try {
        return j.read(str.replace("'", "\""));
    } catch (IOException e) {
        throw new RuntimeException("Failed to create a geometry from given str " + str, e);
    }
}
 
Example #24
Source Project: jts   Author: metteo   File: GeoJson.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void check() {
	GeoJsonReader r = new GeoJsonReader();
	Geometry g;
	try {
		g = r.read("{\"type\":\"Point\", \"coordinates\":[10, 20]}");
		sLogger.info(g.toString());
	} catch (ParseException e) {
		sLogger.log(Level.WARNING, "Problem while parsing GeoJSON", e);
	}
	
}
 
Example #25
Source Project: jts   Author: metteo   File: AbstractIndexedLineTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void runIndexOfAfterTest(String inputStr,
      String testPtWKT, String afterPtWKT)
//        throws Exception
    {
      Geometry input = read(inputStr);
      Geometry testPoint = read(testPtWKT);
      Coordinate testPt = testPoint.getCoordinate();
      Geometry afterPoint = read(afterPtWKT);
      Coordinate afterPt = afterPoint.getCoordinate();
      boolean resultOK = indexOfAfterCheck(input, testPt, afterPt);
      assertTrue(resultOK);
    }
 
Example #26
Source Project: jts   Author: metteo   File: StressTestHarness.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void run(int nIter, Geometry target) {
  	int count = 0;
  	while (count < nIter) {
  		count++;
  		Geometry test = createRandomTestGeometry(target.getEnvelopeInternal(), 10, 20);
      
//      System.out.println("Test # " + count);
//  		System.out.println(line);
//  		System.out.println("Test[" + count + "] " + target.getClass() + "/" + test.getClass());
  		boolean isResultCorrect = checkResult(target, test);
  		if (! isResultCorrect) {
  			throw new RuntimeException("Invalid result found");
  		}
  	}
	}
 
Example #27
Source Project: coordination_oru   Author: FedericoPecora   File: PathEditor2.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Geometry makeFootprint(double x, double y, double theta) {
	AffineTransformation at = new AffineTransformation();
	at.rotate(theta);
	at.translate(x,y);
	Geometry rect = at.transform(PP_footprintGeom);
	return rect;
}
 
Example #28
Source Project: jts   Author: metteo   File: MiscellaneousTest2.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testQuickPolygonUnion() throws Exception {
  Geometry a = reader.read("POLYGON((0 0, 100 0, 100 100, 0 100, 0 0))");
  Geometry b = reader.read("POLYGON((50 50, 150 50, 150 150, 50 150, 50 50))");
  Geometry[] polygons = new Geometry[] {a, b};
  GeometryCollection polygonCollection = new GeometryFactory().createGeometryCollection(polygons);
  Geometry union = polygonCollection.buffer(0);
  System.out.println(union);
  assertEquals("POLYGON ((0 0, 0 100, 50 100, 50 150, 150 150, 150 50, 100 50, 100 0, 0 0))", union.toString());
}
 
Example #29
Source Project: jts   Author: metteo   File: BufferFunctions.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Geometry singleSidedBufferCurve(Geometry geom, double distance) {
  BufferParameters bufParam = new BufferParameters();
  bufParam.setSingleSided(true);
  OffsetCurveBuilder ocb = new OffsetCurveBuilder(
      geom.getFactory().getPrecisionModel(), bufParam
      );
  Coordinate[] pts = ocb.getLineCurve(geom.getCoordinates(), distance);
  Geometry curve = geom.getFactory().createLineString(pts);
  return curve;
}
 
Example #30
Source Project: gama   Author: gama-platform   File: GamaSVGFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void fillBuffer(final IScope scope) throws GamaRuntimeException {
	try (BufferedReader in = new BufferedReader(new FileReader(getFile(scope)))) {
		final SVGUniverse svg = SVGCache.getSVGUniverse();
		final URI uri = svg.loadSVG(in, getPath(scope));
		final SVGDiagram diagram = svg.getDiagram(uri);
		final Shape shape = diagram.getRoot().getShape();
		final Geometry geom = ShapeReader.read(shape, 1.0, GeometryUtils.GEOMETRY_FACTORY); // flatness
		// =
		// ??
		// We center and scale the shape in the same operation
		// final Envelope env = geom.getEnvelopeInternal();
		// GamaPoint translation = new GamaPoint(-env.getWidth() / 2,
		// -env.getHeight() / 2);
		final IShape gs = new GamaShape(null, geom, null, new GamaPoint(0, 0), size, true);
		// gs.setLocation(new GamaPoint(0, 0));
		// gs.setLocation(translation);
		// if ( size != null ) {
		// gs = Spatial.Transformations.scaled_to(scope, gs, size);
		// }
		setBuffer(GamaListFactory.wrap(Types.GEOMETRY, gs));
	} catch (final IOException e) {
		throw GamaRuntimeException.create(e, scope);
		// e.printStackTrace();
	}
}