com.vividsolutions.jts.io.WKTReader Java Examples

The following examples show how to use com.vividsolutions.jts.io.WKTReader. 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: GeometryInputDialog.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
Geometry parseGeometry(JTextComponent txt, Color clr) {
    try {
        WKTReader rdr =
            new WKTReader(
                new GeometryFactory(JTSTestBuilder.model().getPrecisionModel(), 0));
        Geometry g = rdr.read(txt.getText());
        txtError.setText("");
        return g;
    } catch (Exception ex) {
        txtError.setText(ex.getMessage());
        txtError.setForeground(clr);
        parseError = true;
        // TODO: display this exception
    }
    return null;
}
 
Example #2
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 #3
Source File: PolygonizeExample.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
void run()
    throws Exception
{
  WKTReader rdr = new WKTReader();
  Collection lines = new ArrayList();

  lines.add(rdr.read("LINESTRING (0 0 , 10 10)"));   // isolated edge
  lines.add(rdr.read("LINESTRING (185 221, 100 100)"));   //dangling edge
  lines.add(rdr.read("LINESTRING (185 221, 88 275, 180 316)"));
  lines.add(rdr.read("LINESTRING (185 221, 292 281, 180 316)"));
  lines.add(rdr.read("LINESTRING (189 98, 83 187, 185 221)"));
  lines.add(rdr.read("LINESTRING (189 98, 325 168, 185 221)"));

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

  Collection polys = polygonizer.getPolygons();

  System.out.println("Polygons formed (" + polys.size() + "):");
  System.out.println(polys);
}
 
Example #4
Source File: TransformGeometryCommandTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testTransformGeometry() throws Exception {
	TransformGeometryRequest request = new TransformGeometryRequest();
	WKTReader reader = new WKTReader();
	Geometry origin = converterService.toDto(reader.read("POLYGON((10 30, 20 30,20 40,10 40,10 30))"));
	request.setGeometry(origin);
	request.setSourceCrs(MERCATOR);
	request.setTargetCrs(LONLAT);
	// execute
	TransformGeometryResponse response = (TransformGeometryResponse) dispatcher.execute(
			TransformGeometryRequest.COMMAND, request, null, "en");
	Geometry transformed = response.getGeometry();
	Envelope bounds = converterService.toInternal(transformed).getEnvelopeInternal();
	Assert.assertEquals(8.983152841195215E-5, bounds.getMinX(), DELTA);
	Assert.assertEquals(2.6949458522981454E-4, bounds.getMinY(), DELTA);
	Assert.assertEquals(1.796630568239043E-4, bounds.getMaxX(), DELTA);
	Assert.assertEquals(3.593261136397527E-4, bounds.getMaxY(), DELTA);
}
 
Example #5
Source File: GeoParseUtils.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Parse GML/wkt literal to Geometry
 *
 * @param statement
 * @return
 * @throws ParseException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static Geometry getGeometry(final Statement statement, GmlToGeometryParser gmlToGeometryParser) throws ParseException {
    // handle GML or WKT
    final Literal lit = getLiteral(statement);
    if (GeoConstants.XMLSCHEMA_OGC_WKT.equals(lit.getDatatype())) {
        final String wkt = lit.getLabel().toString();
        return (new WKTReader()).read(wkt);
    } else if (GeoConstants.XMLSCHEMA_OGC_GML.equals(lit.getDatatype())) {
        final String gml = lit.getLabel().toString();
        try {
            return getGeometryGml(gml, gmlToGeometryParser);
        } catch (IOException | SAXException | ParserConfigurationException e) {
            throw new ParseException(e);
        }
    } else {
        throw new ParseException("Literal is unknown geo type, expecting WKT or GML: " + statement.toString());
    }
}
 
Example #6
Source File: ProcessingUtils.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Check JTS Footprint validity
 */
public static boolean checkJTSFootprint (String footprint)
{
   try
   {
      WKTReader wkt = new WKTReader();
      Geometry geom = wkt.read(footprint);
      IsValidOp vaildOp = new IsValidOp(geom);
      TopologyValidationError err = vaildOp.getValidationError();
      if (err != null)
      {
         throw new IllegalParameterException(err.getMessage());
      }
      return true;
   }
   catch (Exception e)
   {
      LOGGER.error("JTS Footprint error : " + e.getMessage());
      return false;
   }
}
 
Example #7
Source File: BasicExample.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void main(String[] args)
    throws Exception
{
  // read a geometry from a WKT string (using the default geometry factory)
  Geometry g1 = new WKTReader().read("LINESTRING (0 0, 10 10, 20 20)");
  System.out.println("Geometry 1: " + g1);

  // create a geometry by specifying the coordinates directly
  Coordinate[] coordinates = new Coordinate[]{new Coordinate(0, 0),
    new Coordinate(10, 10), new Coordinate(20, 20)};
  // use the default factory, which gives full double-precision
  Geometry g2 = new GeometryFactory().createLineString(coordinates);
  System.out.println("Geometry 2: " + g2);

  // compute the intersection of the two geometries
  Geometry g3 = g1.intersection(g2);
  System.out.println("G1 intersection G2: " + g3);
}
 
Example #8
Source File: SimpleDemo.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void showPoland() {
	WKTReader r = new WKTReader();
	try {
		Geometry g = r.read(s);
		g.setSRID(4326);

		Geometry g2 = g.buffer(1);
		Geometry g3 = g2.difference(g);

		JavaScriptObject f1 = parseWKT(g.toString());
		JavaScriptObject f2 = parseWKT(g3.toString());
		JsArray<JavaScriptObject> fs = JsArray.createArray().cast();
		fs.push(f1);
		fs.push(f2);

		addFeatures(mMap, fs);
	} catch (ParseException e) {
		sLogger.log(Level.WARNING, "Unable to parse wkb", e);
	}
}
 
Example #9
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 #10
Source File: GeometryType.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * @see liquibase.datatype.LiquibaseDataType#sqlToObject(java.lang.String,
 *      liquibase.database.Database)
 */
@Override
public Object sqlToObject(final String value, final Database database) {
   final Geometry returnValue;
   if (value == null || value.equalsIgnoreCase("null")) {
      returnValue = null;
   } else {
      final WKTReader reader = new WKTReader();
      try {
         // TODO: Check for SRID.
         returnValue = reader.read(value);
      } catch (final ParseException e) {
         throw new UnexpectedLiquibaseException("Cannot parse " + value + " to a Geometry", e);
      }
   }
   return returnValue;
}
 
Example #11
Source File: GeoToolsFeatureModelTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSetGeometry() throws Exception {
	WKTReader wktReader = new WKTReader();
	Point pt = (Point) wktReader.read("POINT (5 5)");
	featureModel.setGeometry(feature, pt);
	Assert.assertEquals(5, featureModel.getGeometry(feature).getCoordinate().x, 0);
}
 
Example #12
Source File: BufferValidator.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Geometry g =
    new WKTReader().read(
      "MULTILINESTRING (( 635074.5418406526 6184832.4888257105, 635074.5681951842 6184832.571842485, 635074.6472587794 6184832.575795664 ), ( 635074.6657069515 6184832.53889932, 635074.6933792098 6184832.451929366, 635074.5642420045 6184832.474330718 ))");
  System.out.println(g);
  System.out.println(g.buffer(0.01, 100));
  System.out.println("END");
}
 
Example #13
Source File: GeoServiceTransformableAreaTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void assertTransformedSingletonCollection(Geometry geometry) throws Exception {
	Geometry other = new WKTReader()
			.read("MULTIPOLYGON (((916070.1613269304 -4681453.714615687, 816814.8052582608" +
					" -3375272.8502673274, 1989027.0198933315 -3206276.455371815, 2262764.0933861886" +
					" -4487305.15962547, 916070.1613269304 -4681453.714615687)))");
	Assert.assertTrue(geometry.equalsExact(other, DELTA));
}
 
Example #14
Source File: LegendGraphicServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private LiteShape2 getSampleShape(Symbolizer symbolizer, int width, int height) {
	MetaBufferEstimator estimator = new MetaBufferEstimator();
	estimator.visit(symbolizer);
	// add an extra pixel to the margin (odd line widths were not always shown)
	int margin = estimator.getBuffer() + 1;
	// we define a shape in WKT of size 1 x 1 and transform it to a rectangle of (width-margin) x (height-margin),
	// to make sure we capture thick strokes
	MathTransform transform = new AffineTransform2D(width - margin, 0, 0, height - margin, 0.5 * margin,
			0.5 * margin);
	try {
		WKTReader wktReader = new WKTReader();
		if (symbolizer instanceof LineSymbolizer) {
			return new LiteShape2(wktReader.read("LINESTRING (0 0, 0.66 0.33, 0.33 0.66, 1 1)"), transform, null,
					false);
		} else if (symbolizer instanceof PolygonSymbolizer) {
			return new LiteShape2(wktReader.read("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))"), transform, null, false);
		} else if (symbolizer instanceof PointSymbolizer) {
			return new LiteShape2(wktReader.read("POINT (0.5 0.5)"), transform, null, false);
		} else {
			return null;
		}
	} catch (Exception e) { // NOSONAR
		// should not happen
		log.warn("Could not create sample shapes", e);
		return null;
	}
}
 
Example #15
Source File: NestedFeatureModelTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setUpTestDataWithinTransaction() throws LayerException, ParseException {
	wktReader = new WKTReader(new GeometryFactory(new PrecisionModel(), 4326));
	featureModel = layer.getFeatureModel();
	feature1 = NestedFeature.getDefaultInstance1();
	feature1.setGeometry(wktReader.read("POINT(10 20)"));
	layer.create(feature1);
}
 
Example #16
Source File: AreaAuthorizationInfo.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private Geometry readWkt(String area) {
	try {
		WKTReader wktReader = new WKTReader(new GeometryFactory(new PrecisionModel(), 0));
		return wktReader.read(area);
	} catch (ParseException pe) {
		throw new IllegalArgumentException("Could not parse geometry " + area, pe);
	}
}
 
Example #17
Source File: ShapeInMemFeatureModelTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void setGeometry() throws Exception {
	WKTReader wktReader = new WKTReader();
	Point pt = (Point) wktReader.read("POINT (5 5)");
	featureModel.setGeometry(feature, pt);
	Assert.assertEquals(5, featureModel.getGeometry(feature).getCoordinate().x, 0.00001);
}
 
Example #18
Source File: GeoToolsLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void create() throws Exception {
	WKTReader wktReader = new WKTReader();
	Point geometry = (Point) wktReader.read("POINT (0 0)");

	SimpleFeatureBuilder build = new SimpleFeatureBuilder(layer.getSchema());
	SimpleFeature feature = build.buildFeature("100000", new Object[] { geometry, "Tsjakamaka", 342 });

	Object created = layer.create(feature);
	Assert.assertNotNull(created);
}
 
Example #19
Source File: GeometryTestCase.java    From jts with 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 #20
Source File: IOUtil.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Geometry read(String wkt)
{
 WKTReader rdr = new WKTReader();
  try {
    return rdr.read(wkt);
  }
  catch (ParseException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #21
Source File: NormalizeTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testNormalizePackedCoordinateSequence() throws Exception {
  GeometryFactory pcsFactory = new GeometryFactory(PackedCoordinateSequenceFactory.DOUBLE_FACTORY);
  WKTReader pcsReader = new WKTReader(pcsFactory);
  Geometry geom = pcsReader.read("LINESTRING (100 100, 0 0)");
  geom.normalize();
  // force PackedCoordinateSequence to be copied with empty coordinate cache
  Geometry copy = (Geometry) geom.copy();
  assertEqualsExact(geom, copy);
}
 
Example #22
Source File: LineStringImplTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testEquals10() throws Exception {
  WKTReader reader = new WKTReader(new GeometryFactory(new PrecisionModel(1), 0));
  Geometry l1 = reader.read("POLYGON((1732328800 519578384, 1732026179 519976285, 1731627364 519674014, 1731929984 519276112, 1732328800 519578384))");
  Geometry l2 = reader.read("POLYGON((1731627364 519674014, 1731929984 519276112, 1732328800 519578384, 1732026179 519976285, 1731627364 519674014))");
  l1.normalize();
  l2.normalize();
  assertTrue(l1.equalsExact(l2));
}
 
Example #23
Source File: GeometryCollectionImplTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testGetLength() throws Exception{
  GeometryCollection g = (GeometryCollection) new WKTReader().read(
        "MULTIPOLYGON("
        + "((0 0, 10 0, 10 10, 0 10, 0 0), (3 3, 3 7, 7 7, 7 3, 3 3)),"
        + "((100 100, 110 100, 110 110, 100 110, 100 100), (103 103, 103 107, 107 107, 107 103, 103 103)))");
  assertEquals(112, g.getLength(), 1E-15);
}
 
Example #24
Source File: GeometryImplTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doTestFromCommcast2003AtYahooDotCa(WKTReader reader)
    throws ParseException {
	readerFloat.read(
        "POLYGON ((708653.498611049 2402311.54647056, 708708.895756966 2402203.47250014, 708280.326454234 2402089.6337791, 708247.896591321 2402252.48269854, 708367.379593851 2402324.00761653, 708248.882609455 2402253.07294874, 708249.523621829 2402244.3124463, 708261.854734465 2402182.39086576, 708262.818392579 2402183.35452387, 708653.498611049 2402311.54647056))")
          .intersection(reader.read(
            "POLYGON ((708258.754920656 2402197.91172757, 708257.029447455 2402206.56901508, 708652.961095455 2402312.65463437, 708657.068786251 2402304.6356364, 708258.754920656 2402197.91172757))"));
}
 
Example #25
Source File: MinimumDiameterTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doMinimumDiameterTest(boolean convex, String wkt, Coordinate c0, Coordinate c1) throws ParseException {
  Coordinate[] minimumDiameter = new MinimumDiameter(new WKTReader().read(wkt), convex).getDiameter().getCoordinates();
  double tolerance = 1E-10;
  assertEquals(c0.x, minimumDiameter[0].x, tolerance);
  assertEquals(c0.y, minimumDiameter[0].y, tolerance);
  assertEquals(c1.x, minimumDiameter[1].x, tolerance);
  assertEquals(c1.y, minimumDiameter[1].y, tolerance);
}
 
Example #26
Source File: DistanceTest.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doNearestPointsTest(String wkt0, String wkt1, double distance, 
                                 Coordinate p0, Coordinate p1) throws ParseException {
  DistanceOp op = new DistanceOp(new WKTReader().read(wkt0), new WKTReader().read(wkt1));
  double tolerance = 1E-10;
  assertEquals(distance, op.nearestPoints()[0].distance(op.nearestPoints()[1]), tolerance);
  assertEquals(p0.x, op.nearestPoints()[0].x, tolerance);
  assertEquals(p0.y, op.nearestPoints()[0].y, tolerance);
  assertEquals(p1.x, op.nearestPoints()[1].x, tolerance);
  assertEquals(p1.y, op.nearestPoints()[1].y, tolerance);    
}
 
Example #27
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 #28
Source File: IOUtil.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Reads one or more WKT geometries from a string.
 * 
 * @param wkt
 * @param geomFact
 * @return the geometry read
 * @throws ParseException
 * @throws IOException
 */
public static Geometry readWKTString(String wkt, GeometryFactory geomFact)
throws ParseException, IOException 
{
  WKTReader reader = new WKTReader(geomFact);
  WKTFileReader fileReader = new WKTFileReader(new StringReader(wkt), reader);
  List geomList = fileReader.read();
  
  if (geomList.size() == 1)
    return (Geometry) geomList.get(0);
  
  return geomFact.createGeometryCollection(GeometryFactory.toGeometryArray(geomList));
}
 
Example #29
Source File: LineStringSelfIntersections.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args)
    throws Exception
{
  WKTReader rdr = new WKTReader();

  LineString line1 = (LineString) (rdr.read("LINESTRING (0 0, 10 10, 20 20)"));
  showSelfIntersections(line1);
  LineString line2 = (LineString) (rdr.read("LINESTRING (0 40, 60 40, 60 0, 20 0, 20 60)"));
  showSelfIntersections(line2);

}
 
Example #30
Source File: PolygonUnionUsingBuffer.java    From jts with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args)
    throws Exception
{
  WKTReader rdr = new WKTReader();

  Geometry[] geom = new Geometry[3];
  geom[0] = rdr.read("POLYGON (( 100 180, 100 260, 180 260, 180 180, 100 180 ))");
  geom[1] = rdr.read("POLYGON (( 80 140, 80 200, 200 200, 200 140, 80 140 ))");
  geom[2] = rdr.read("POLYGON (( 160 160, 160 240, 240 240, 240 160, 160 160 ))");
  unionUsingBuffer(geom);

}