下面列出了org.json.simple.JSONAware#com.vividsolutions.jts.geom.Geometry 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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);
}
}
}
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[]{});
}
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();
}
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()));
}
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);
}
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);
}
@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 ) );
}
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());
}
/**
* 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));
}
/**
* 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();
}
/**
* 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;
}
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);
}
}
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);
}
/**
* @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;
}
/**
* 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);
}
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;
}
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);
}
/**
* 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());
}
}
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();
}
}
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);
}
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);
}
}
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);
}
}
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);
}
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");
}
}
}
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;
}
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());
}
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;
}
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;
}
@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();
}
}