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 File: GamaGisFile.java    From gama with GNU General Public License v3.0 8 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 File: GeoTemporalMongoDBStorageStrategy.java    From rya with 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 #3
Source File: BeanFeatureModel.java    From geomajas-project-server with 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 File: DivideLineStringTool.java    From geowe-core with 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 #5
Source File: UserMapper.java    From C4SG-Obsolete with MIT License 5 votes vote down vote up
/**
 * Map user entity into data transfer object
 * 
 * @param user User Entity
 * @return UserDTO
 */
public UserDTO getUserDtoFromEntity(User user){
	//convert geometry object to a point
	Geometry g = null;
	com.vividsolutions.jts.geom.Point point = null;		
	WKTReader reader = new WKTReader();
	try {
		g = reader.read(user.getLocation().toText());
		point = (com.vividsolutions.jts.geom.Point) g;
	}
	catch (Exception e) {
		//do nothing
	}
	//start mapping data into the dto
	if (user == null)
		return null;
	
	UserDTO userDTO = map(user, UserDTO.class);
	//add mapping for location if point object is not null
	if (point != null) {
		org.springframework.data.geo.Point gp = new Point(point.getX(), point.getY());
		userDTO.setLongitude(Double.toString(point.getX()));
		userDTO.setLatitude(Double.toString(point.getY()));
	}
	userDTO.setDisplayFlag((user.getDisplayFlag() != null && user.getDisplayFlag().booleanValue()) ? "Y" : "N");
	return userDTO;
}
 
Example #6
Source File: GeometryUtils.java    From gama with 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 #7
Source File: GeometryResult.java    From jts with 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 #8
Source File: GeometryPrecisionReducerTest.java    From jts with 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 #9
Source File: Disruption.java    From product-cep with 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 #10
Source File: GeoJson.java    From jts with 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 #11
Source File: AbstractIndexedLineTest.java    From jts with 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 #12
Source File: JTSTestBuilderFrame.java    From jts with 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 #13
Source File: PathEditor2.java    From coordination_oru with 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 #14
Source File: MiscellaneousTest2.java    From jts with 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 #15
Source File: BufferFunctions.java    From jts with 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 #16
Source File: GamaSVGFile.java    From gama with 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();
	}
}
 
Example #17
Source File: AbstractJTSService.java    From geowe-core with GNU General Public License v3.0 5 votes vote down vote up
protected Geometry getGeometry(final String wkt) {
	Geometry geom = null;
	final GeometryFactory factory = new GeometryFactory(
			PackedCoordinateSequenceFactory.DOUBLE_FACTORY);
	final WKTReader reader = new WKTReader(factory);
	try {
		geom = reader.read(wkt);
	} catch (ParseException e) {			
		LOG.error(INVALID_WKT_MESSAGE + e.getMessage());
		throw new IllegalArgumentException(INVALID_WKT_MESSAGE, e);
	}

	return geom;
}
 
Example #18
Source File: StressTestHarness.java    From jts with 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 #19
Source File: DividePolygonTool.java    From geowe-core with GNU General Public License v3.0 5 votes vote down vote up
public List<String> divide(final String wktCorte, final String wktIntersected)
		throws IllegalArgumentException {

	final List<String> wkts = new ArrayList<String>();
	try {
		final Geometry geomCorte = getGeometry(wktCorte);
		final Geometry geomIntersected = getGeometry(wktIntersected);

		if (geomIntersected == null || geomCorte == null) {
			throw new RuntimeException("Existen geometrĂ­a nulas");
		}

		final Collection<Geometry> lines = getLines((Polygon) geomIntersected, (LineString) geomCorte);
		final Collection<Geometry> nodedLines = lineNoder.nodeLines(lines);			
		final Collection<Geometry> polygons = lineNoder.polygonizer(nodedLines);

		for (final Geometry pol : polygons) {
			wkts.add(pol.toText());
		}

	} catch (Exception e) {
		throw new IllegalArgumentException("Error no controlado: "
				+ e.getMessage(), e);
	}

	return wkts;
}
 
Example #20
Source File: GeometryPainter.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void paint(Geometry geometry, Viewport viewport, 
    Graphics2D g,
    Color lineColor, Color fillColor, Stroke stroke) 
{
  ShapeWriter converter = getConverter(viewport);
  //ShapeWriter converter = new ShapeWriter(viewport);
  paint(geometry, converter, g, lineColor, fillColor, stroke);
}
 
Example #21
Source File: CGAlgorithmFunctions.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean segmentIntersects(Geometry g1, Geometry g2)
{
  Coordinate[] pt1 = g1.getCoordinates();
  Coordinate[] pt2 = g2.getCoordinates();
  RobustLineIntersector ri = new RobustLineIntersector();
  ri.computeIntersection(pt1[0], pt1[1], pt2[0], pt2[1]);
  return ri.hasIntersection();
}
 
Example #22
Source File: CachedBABDistance.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
static double getDistance(Geometry g1, Geometry g2)
{
  if (cacheGeom != g1) {
    babDist = new IndexedFacetDistance(g1);
    cacheGeom = g1;
  }
  return babDist.getDistance(g2);
}
 
Example #23
Source File: SimpleGeometryPrecisionReducerTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSquareCollapse()
    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 = reducer.reduce(g);
  assertTrue(gReduce.equalsExact(g2));
}
 
Example #24
Source File: PreparedPolygonPredicateStressTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean checkContains(Geometry target, Geometry test) 
 {
boolean expectedResult = target.contains(test);

   PreparedGeometryFactory pgFact = new PreparedGeometryFactory();
   PreparedGeometry prepGeom = pgFact.create(target);
   
boolean prepResult = prepGeom.contains(test);

if (prepResult != expectedResult) {
	return false;
}
return true;
 }
 
Example #25
Source File: QuadEdgeTriangle.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Geometry toPolygon(Vertex[] v) {
	Coordinate[] ringPts = new Coordinate[] { v[0].getCoordinate(),
			v[1].getCoordinate(), v[2].getCoordinate(), v[0].getCoordinate() };
	GeometryFactory fact = new GeometryFactory();
	LinearRing ring = fact.createLinearRing(ringPts);
	Polygon tri = fact.createPolygon(ring, null);
	return tri;
}
 
Example #26
Source File: CoordinateUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String getCoordinatesFromGeometry( Geometry geometry )
{
    String coordinatesKey = "\"coordinates\":";
    String crsKey = ",\"crs\":";

    GeoJsonWriter gjw = new GeoJsonWriter(  );
    String geojson = gjw.write( geometry ).trim();

    return geojson.substring( geojson.indexOf( coordinatesKey ) + coordinatesKey.length(), geojson.indexOf( crsKey ) );
}
 
Example #27
Source File: WorldProjection.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void inverseTranslate(final Geometry geom) {
	if (absoluteToGisTranslation != null) {
		geom.apply(absoluteToGisTranslation);
		geom.geometryChanged();
	}
}
 
Example #28
Source File: BufferByUnionFunctions.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Geometry bufferByChains(Geometry g, double distance, int maxChainSize)
{
  if (maxChainSize <= 0)
    throw new IllegalArgumentException("Maximum Chain Size must be specified as an input parameter");
  Geometry segs = LineHandlingFunctions.extractChains(g, maxChainSize);
  double posDist = Math.abs(distance);
  Geometry segBuf = bufferByComponents(segs, posDist);
  if (distance < 0.0) 
    return g.difference(segBuf);
  return g.union(segBuf);
}
 
Example #29
Source File: LayerList.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Geometry extractComponents(Geometry parentGeom, Geometry aoi)
{
  ComponentLocater locater = new ComponentLocater(parentGeom);
  List locs = locater.getComponents(aoi);
  List geoms = extractLocationGeometry(locs);
  if (geoms.size() <= 0)
    return null;
  if (geoms.size() == 1) 
    return (Geometry) geoms.get(0);
  // if parent was a GC, ensure returning a GC
  if (parentGeom.getGeometryType().equals("GeometryCollection"))
    return parentGeom.getFactory().createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
  // otherwise return MultiGeom
  return parentGeom.getFactory().buildGeometry(geoms);
}
 
Example #30
Source File: GamaGeometryType.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param xRadius
 * @param heading
 *            in decimal degrees
 * @param amplitude
 *            in decimal degrees
 * @param filled
 * @param location
 * @return
 */
public static IShape buildArc(final double xRadius, final double heading, final double amplitude,
		final boolean filled, final GamaPoint location) {
	if (amplitude <= 0 || xRadius <= 0) { return new GamaShape(location); }
	final GeometricShapeFactory factory = new GeometricShapeFactory(GeometryUtils.GEOMETRY_FACTORY);
	factory.setNumPoints(GamaPreferences.Displays.DISPLAY_SLICE_NUMBER.getValue()); // WARNING AD Arbitrary number.
																					// Maybe add a
	// parameter and/or preference ?
	factory.setCentre(location);
	factory.setSize(xRadius);
	final double ampl = Maths.checkHeading(amplitude);

	final double angExtent = Maths.toRad * ampl;
	final double startAng = Maths.toRad * Maths.checkHeading(heading - ampl / 2);
	Geometry g;
	if (filled) {
		g = factory.createArcPolygon(startAng, angExtent);
	} else {
		g = factory.createArc(startAng, angExtent);
	}
	if (location != null) {
		final Coordinate[] coordinates = g.getCoordinates();
		for (int i = 0; i < coordinates.length; i++) {
			coordinates[i].z = location.z;
		}
	}
	return new GamaShape(g);

}