com.vividsolutions.jts.io.WKTWriter Java Examples

The following examples show how to use com.vividsolutions.jts.io.WKTWriter. 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 void iterateOverTriangles(final Polygon polygon, final Consumer<Geometry> action) {
	final double elevation = getContourCoordinates(polygon).averageZ();
	final double sizeTol = Math.sqrt(polygon.getArea()) / 100.0;
	final DelaunayTriangulationBuilder dtb = new DelaunayTriangulationBuilder();
	final PreparedGeometry buffered = PREPARED_GEOMETRY_FACTORY.create(polygon.buffer(sizeTol, 5, 0));
	final Envelope3D env = Envelope3D.of(buffered.getGeometry());
	try {
		dtb.setSites(polygon);
		dtb.setTolerance(sizeTol);
		applyToInnerGeometries(dtb.getTriangles(GEOMETRY_FACTORY), (gg) -> {
			final ICoordinates cc = getContourCoordinates(gg);
			if (cc.isCoveredBy(env) && buffered.covers(gg)) {
				cc.setAllZ(elevation);
				gg.geometryChanged();
				action.accept(gg);
			}
		});
	} catch (final LocateFailureException | ConstraintEnforcementException e) {
		final IScope scope = GAMA.getRuntimeScope();
		GamaRuntimeException.warning("Impossible to triangulate: " + new WKTWriter().write(polygon), scope);
		iterateOverTriangles((Polygon) DouglasPeuckerSimplifier.simplify(polygon, 0.1), action);
		return;
	} finally {
		env.dispose();
	}
}
 
Example #2
Source File: TestCase.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String toXml() {
  WKTWriter writer = new WKTWriter();
  String xml = "";
  xml += "<case>" + StringUtil.newLine;
  if (description != null && description.length() > 0) {
    xml += "  <desc>" + StringUtil.escapeHTML(description) + "</desc>" +
        StringUtil.newLine;
  }
  xml += xml("a", a, aWktFile, writer) + StringUtil.newLine;
  xml += xml("b", b, bWktFile, writer);
  for (Iterator i = tests.iterator(); i.hasNext(); ) {
    Test test = (Test) i.next();
    xml += test.toXml();
  }
  xml += "</case>" + StringUtil.newLine;
  return xml;
}
 
Example #3
Source File: QuadEdgeSubdivision.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkTriangleSize(Coordinate[] pts)
{
	String loc = "";
	if (pts.length >= 2)
		loc = WKTWriter.toLineString(pts[0], pts[1]);
	else {
		if (pts.length >= 1)
			loc = WKTWriter.toPoint(pts[0]);
	}
	// Assert.isTrue(pts.length == 4, "Too few points for visited triangle at " + loc);
	//com.vividsolutions.jts.util.Debug.println("too few points for triangle at " + loc);
}
 
Example #4
Source File: BeanFeatureModel.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void setGeometry(Object feature, Geometry geometry) throws LayerException {
	Entity entity = entityMapper.asEntity(feature);
	if (wkt) {
		WKTWriter writer = new WKTWriter();
		String wktStr = null;
		if (null != geometry) {
			wktStr = writer.write(geometry);
		}
		entity.setAttribute(getGeometryAttributeName(), wktStr);
	} else {
		entity.setAttribute(getGeometryAttributeName(), geometry);
	}
}
 
Example #5
Source File: FileBufferResultValidatorTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
void runBuffer(Geometry g, double dist)
{
	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()));
    System.out.println(g);
  }
	assertTrue(validator.isValid());
}
 
Example #6
Source File: TriPredicate.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   * Checks if the computed value for isInCircle is correct, using
   * double-double precision arithmetic.
   * 
   * @param a a vertex of the triangle
   * @param b a vertex of the triangle
   * @param c a vertex of the triangle
   * @param p the point to test
   */
private static void checkRobustInCircle(Coordinate a, Coordinate b, Coordinate c,
    Coordinate p) 
{
  boolean nonRobustInCircle = isInCircle(a, b, c, p);
  boolean isInCircleDD = TriPredicate.isInCircleDD(a, b, c, p);
  boolean isInCircleCC = TriPredicate.isInCircleCC(a, b, c, p);

  Coordinate circumCentre = Triangle.circumcentre(a, b, c);
  System.out.println("p radius diff a = "
      + Math.abs(p.distance(circumCentre) - a.distance(circumCentre))
      / a.distance(circumCentre));

  if (nonRobustInCircle != isInCircleDD || nonRobustInCircle != isInCircleCC) {
    System.out.println("inCircle robustness failure (double result = "
        + nonRobustInCircle 
        + ", DD result = " + isInCircleDD
        + ", CC result = " + isInCircleCC + ")");
    System.out.println(WKTWriter.toLineString(new CoordinateArraySequence(
        new Coordinate[] { a, b, c, p })));
    System.out.println("Circumcentre = " + WKTWriter.toPoint(circumCentre)
        + " radius = " + a.distance(circumCentre));
    System.out.println("p radius diff a = "
        + Math.abs(p.distance(circumCentre)/a.distance(circumCentre) - 1));
    System.out.println("p radius diff b = "
        + Math.abs(p.distance(circumCentre)/b.distance(circumCentre) - 1));
    System.out.println("p radius diff c = "
        + Math.abs(p.distance(circumCentre)/c.distance(circumCentre) - 1));
    System.out.println();
  }
}
 
Example #7
Source File: BufferResultValidatorTest.java    From jts with 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 #8
Source File: AkGeometry.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void formatAsLiteral(TInstance type, ValueSource source, AkibanAppender out) {
    StringWriter sw = new StringWriter();
    try {
        new WKTWriter(Spatial.LAT_LON_DIMENSIONS).write((Geometry)source.getObject(),
                                                        sw);
    }
    catch (IOException ex) {
        throw new AkibanInternalException("Error formatting to string", ex);
    }
    out.append('\'');
    out.append(sw.toString());
    out.append('\'');
}
 
Example #9
Source File: TrianglePredicate.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   * Checks if the computed value for isInCircle is correct, using
   * double-double precision arithmetic.
   * 
   * @param a a vertex of the triangle
   * @param b a vertex of the triangle
   * @param c a vertex of the triangle
   * @param p the point to test
   */
private static void checkRobustInCircle(Coordinate a, Coordinate b, Coordinate c,
    Coordinate p) 
{
  boolean nonRobustInCircle = isInCircleNonRobust(a, b, c, p);
  boolean isInCircleDD = TrianglePredicate.isInCircleDDSlow(a, b, c, p);
  boolean isInCircleCC = TrianglePredicate.isInCircleCC(a, b, c, p);

  Coordinate circumCentre = Triangle.circumcentre(a, b, c);
  System.out.println("p radius diff a = "
      + Math.abs(p.distance(circumCentre) - a.distance(circumCentre))
      / a.distance(circumCentre));

  if (nonRobustInCircle != isInCircleDD || nonRobustInCircle != isInCircleCC) {
    System.out.println("inCircle robustness failure (double result = "
        + nonRobustInCircle 
        + ", DD result = " + isInCircleDD
        + ", CC result = " + isInCircleCC + ")");
    System.out.println(WKTWriter.toLineString(new CoordinateArraySequence(
        new Coordinate[] { a, b, c, p })));
    System.out.println("Circumcentre = " + WKTWriter.toPoint(circumCentre)
        + " radius = " + a.distance(circumCentre));
    System.out.println("p radius diff a = "
        + Math.abs(p.distance(circumCentre)/a.distance(circumCentre) - 1));
    System.out.println("p radius diff b = "
        + Math.abs(p.distance(circumCentre)/b.distance(circumCentre) - 1));
    System.out.println("p radius diff c = "
        + Math.abs(p.distance(circumCentre)/c.distance(circumCentre) - 1));
    System.out.println();
  }
}
 
Example #10
Source File: GeoFilterIT.java    From rya with Apache License 2.0 5 votes vote down vote up
private static Statement statement(final Geometry geo) {
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Resource subject = vf.createIRI("urn:event1");
    final IRI predicate = GeoConstants.GEO_AS_WKT;
    final WKTWriter w = new WKTWriter();
    final Value object = vf.createLiteral(w.write(geo), GeoConstants.XMLSCHEMA_OGC_WKT);
    return vf.createStatement(subject, predicate, object);
}
 
Example #11
Source File: GeoFilterIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void showProcessorWorks() throws Exception {
    // Enumerate some topics that will be re-used
    final String ryaInstance = UUID.randomUUID().toString();
    final UUID queryId = UUID.randomUUID();
    final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
    final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);

    // Get the RDF model objects that will be used to build the query.
    final String sparql =
            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>\n"
                    + "PREFIX geof: <" + GEO + ">\n"
                    + "SELECT * \n"
                    + "WHERE { \n"
                    + "  <urn:event1> geo:asWKT ?point .\n"
                    + " FILTER(geof:sfWithin(?point, \"POLYGON((-3 -2, -3 2, 1 2, 1 -2, -3 -2))\"^^geo:wktLiteral)) "
                    + "}";

    // Setup a topology.
    final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());

    // Create the statements that will be input into the query.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final List<VisibilityStatement> statements = getStatements();

    // Make the expected results.
    final Set<VisibilityBindingSet> expected = new HashSet<>();
    final MapBindingSet bs = new MapBindingSet();
    final WKTWriter w = new WKTWriter();
    bs.addBinding("point", vf.createLiteral(w.write(ZERO), GeoConstants.XMLSCHEMA_OGC_WKT));
    expected.add( new VisibilityBindingSet(bs, "a") );

    // Run the test.
    RyaStreamsTestUtil.runStreamProcessingTest(kafka, statementsTopic, resultsTopic, builder, statements, expected, VisibilityBindingSetDeserializer.class);
}
 
Example #12
Source File: MongoGeoIndexerFilterIT.java    From rya with Apache License 2.0 5 votes vote down vote up
private static RyaStatement statement(final Geometry geo) {
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Resource subject = vf.createIRI("urn:geo");
    final IRI predicate = GeoConstants.GEO_AS_WKT;
    final WKTWriter w = new WKTWriter();
    final Value object = vf.createLiteral(w.write(geo), GeoConstants.XMLSCHEMA_OGC_WKT);
    return RdfToRyaConversions.convertStatement(vf.createStatement(subject, predicate, object));
}
 
Example #13
Source File: MongoIndexerDeleteIT.java    From rya with Apache License 2.0 5 votes vote down vote up
private static RyaStatement statement(final Geometry geo) {
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Resource subject = vf.createIRI("urn:geo");
    final IRI predicate = GeoConstants.GEO_AS_WKT;
    final WKTWriter w = new WKTWriter();
    final Value object = vf.createLiteral(w.write(geo), GeoConstants.XMLSCHEMA_OGC_WKT);
    return RdfToRyaConversions.convertStatement(vf.createStatement(subject, predicate, object));
}
 
Example #14
Source File: OverlayValidatedGeometryOperation.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void validate(int opCode, Geometry g0, Geometry g1, Geometry result)
{
 OverlayResultValidator validator = new OverlayResultValidator(g0, g1, result);
 // check if computed result is valid
 if (! validator.isValid(opCode)) {
 	Coordinate invalidLoc = validator.getInvalidLocation();
 	String msg = "Operation result is invalid [OverlayResultValidator] ( " + WKTWriter.toPoint(invalidLoc) + " )";
 	reportError(msg);
 } 
}
 
Example #15
Source File: NodedSegmentString.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String toString()
{
	return WKTWriter.toLineString(new CoordinateArraySequence(pts));
}
 
Example #16
Source File: JTSFootprintParser.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Cut given polygon on poles (89 and -89)
 */
private static String cutOnPoles(String polygonWKT) throws Exception
{
   JtsSpatialContextFactory noCheckFactory = new JtsSpatialContextFactory();
   noCheckFactory.datelineRule = DatelineRule.none;
   noCheckFactory.validationRule = ValidationRule.none;
   JtsSpatialContext noCheckContext = noCheckFactory.newSpatialContext();
   JtsWKTReaderShapeParser noCheckParser =
         new JtsWKTReaderShapeParser(noCheckContext, noCheckFactory);

   JtsGeometry polygon = (JtsGeometry) noCheckParser.parse(polygonWKT);
   JtsGeometry northPole =
         (JtsGeometry) noCheckParser.parse("LINESTRING(180 89, 0 89, -180 89)");
   JtsGeometry southPole =
         (JtsGeometry) noCheckParser.parse("LINESTRING(180 -89, 0 -89, -180 -89)");

   LineMerger lm = new LineMerger();
   lm.add(polygon.getGeom());
   lm.add(northPole.getGeom());
   lm.add(southPole.getGeom());

   Geometry geometry = UnaryUnionOp.union(lm.getMergedLineStrings());

   Polygonizer polygonizer = new Polygonizer();
   polygonizer.add(geometry);

   List<Polygon> foundPolygons = (List<Polygon>) polygonizer.getPolygons();
   List<Polygon> filteredPolygons = new ArrayList<>();
   for (Polygon p: foundPolygons)
   {
      // removing polygons over the poles
      if (p.getCentroid().getCoordinate().y < 89 && p.getCentroid().getCoordinate().y > -89)
      {
         filteredPolygons.add(p);
      }
   }

   Geometry res = null;

   if (!filteredPolygons.isEmpty())
   {
      res = filteredPolygons.get(0);
   }
   if (filteredPolygons.size() > 1)
   {
      // Should not happen...
      LOGGER.error("A Multipolygon was found, instead of a single polygon. Only the first one is retained.");
   }

   WKTWriter wkw = new WKTWriter();
   return wkw.write(res);
}
 
Example #17
Source File: SpatialSupportInitializer.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public String toWkt(Shape s) throws IOException {
    return new WKTWriter().write(context.getGeometryFrom(s));
}
 
Example #18
Source File: UnionPerfTester.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
void printFormatted(Geometry geom)
{
	WKTWriter writer = new WKTWriter();
	System.out.println(writer.writeFormatted(geom));
}
 
Example #19
Source File: SortedPackedIntervalRTree.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void printNode(IntervalRTreeNode node)
{
  System.out.println(WKTWriter.toLineString(new Coordinate(node.min, level), new Coordinate(node.max, level)));
}
 
Example #20
Source File: BasicSegmentString.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String toString()
{
  return WKTWriter.toLineString(new CoordinateArraySequence(pts));
}
 
Example #21
Source File: PointPairDistance.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String toString()
{
	return WKTWriter.toLineString(pt[0], pt[1]);
}
 
Example #22
Source File: LineIntersector.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String toString() {
  return WKTWriter.toLineString(inputLines[0][0], inputLines[0][1]) + " - "
  + WKTWriter.toLineString(inputLines[1][0], inputLines[1][1])
               + getTopologySummary();
}
 
Example #23
Source File: ConstraintEnforcementException.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static String msgWithCoord(String msg, Coordinate pt) {
    if (pt != null)
        return msg + " [ " + WKTWriter.toPoint(pt) + " ]";
    return msg;
}
 
Example #24
Source File: GeometryResult.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String toFormattedString() {
  WKTWriter writer = new WKTWriter();
  return writer.writeFormatted(geometry);
}
 
Example #25
Source File: HsqlGeometryUserType.java    From geomajas-project-server with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Converts a JTS <code>Geometry</code> to a native geometry object.
 * 
 * @param jtsGeom
 *            JTS Geometry to convert
 * @param connection
 *            the current database connection
 * @return native database geometry object corresponding to jtsGeom.
 */
public Object conv2DBGeometry(Geometry jtsGeom, Connection connection) {
	int srid = jtsGeom.getSRID();
	WKTWriter writer = new WKTWriter();
	String wkt = writer.write(jtsGeom);
	return srid + "|" + wkt;
}
 
Example #26
Source File: Geometry.java    From jts with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 *  Returns the Well-known Text representation of this <code>Geometry</code>.
 *  For a definition of the Well-known Text format, see the OpenGIS Simple
 *  Features Specification.
 *
 *@return    the Well-known Text representation of this <code>Geometry</code>
 */
public String toText() {
  WKTWriter writer = new WKTWriter();
  return writer.write(this);
}
 
Example #27
Source File: QuadEdge.java    From jts with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Converts this edge to a WKT two-point <tt>LINESTRING</tt> indicating 
 * the geometry of this edge.
 * 
 * @return a String representing this edge's geometry
 */
public String toString() {
    Coordinate p0 = vertex.getCoordinate();
    Coordinate p1 = dest().getCoordinate();
    return WKTWriter.toLineString(p0, p1);
}
 
Example #28
Source File: EdgeRing.java    From jts with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Gets a string representation of this object.
 * 
 * @return a string representing the object 
 */
public String toString() {
  return WKTWriter.toLineString(new CoordinateArraySequence(getCoordinates()));
}
 
Example #29
Source File: SimpleDemo.java    From jts with GNU Lesser General Public License v2.1 2 votes vote down vote up
private Geometry demonstrateGeometryAndWktWriter() {
	GeometryFactory gf = new GeometryFactory();

	WKTWriter wkt2 = new WKTWriter();

	WKTWriter wkt3 = new WKTWriter(3);

	Coordinate c1 = new Coordinate(1234234.233442, 2234234.234234,
			3323424.2342342);
	Point p = gf.createPoint(c1);

	sLogger.info("Point WKT: " + wkt2.write(p));
	sLogger.info("Point WKT3: " + wkt3.write(p));

	Coordinate c2 = new Coordinate(4234234.233442, 5234223.234234,
			5323424.2342342);

	Coordinate[] c3 = new Coordinate[] { c1, c2 };

	MultiPoint mp = gf.createMultiPoint(c3);

	sLogger.info("Point WKT: " + wkt2.write(mp));
	sLogger.info("Point WKT3: " + wkt3.write(mp));

	LineString ls = gf.createLineString(c3);

	sLogger.info("Point WKT: " + wkt2.write(ls));
	sLogger.info("Point WKT3: " + wkt3.write(ls));

	MultiLineString mls = gf.createMultiLineString(new LineString[] { ls,
			ls });

	sLogger.info("Point WKT: " + wkt2.write(mls));
	sLogger.info("Point WKT3: " + wkt3.write(mls));

	Coordinate c4 = new Coordinate(6234234.233442, 8234234.234234,
			9323424.2342342);
	Coordinate[] c5 = new Coordinate[] { c1, c2, c4, c1 };

	Polygon poly = gf.createPolygon(c5);

	sLogger.info("Point WKT: " + wkt2.write(poly));
	sLogger.info("Point WKT3: " + wkt3.write(poly));

	MultiPolygon mpoly = gf
			.createMultiPolygon(new Polygon[] { poly, poly });

	sLogger.info("Point WKT: " + wkt2.write(mpoly));
	sLogger.info("Point WKT3: " + wkt3.write(mpoly));

	GeometryCollection gc = gf.createGeometryCollection(new Geometry[] { p,
			mp, ls, mls, poly, mpoly });

	sLogger.info("Point WKT: " + wkt2.write(gc));
	sLogger.info("Point WKT3: " + wkt3.write(gc));

	return gc;
}