public void testHomogeneous() throws Exception { Node node = createNode( gcol, new ElementInstance[] {point1, point2}, new Object[] { gf.createPoint(new Coordinate(0, 0)), gf.createPoint(new Coordinate(1, 1)) }, null, null); GMLGeometryCollectionTypeBinding s = (GMLGeometryCollectionTypeBinding) container.getComponentInstanceOfType(GMLGeometryCollectionTypeBinding.class); GeometryCollection gc = (GeometryCollection) s.parse(gcol, node, null); assertNotNull(gc); assertEquals(gc.getNumGeometries(), 2); assertTrue(gc.getGeometryN(0) instanceof Point); assertTrue(gc.getGeometryN(1) instanceof Point); assertEquals(((Point) gc.getGeometryN(0)).getX(), 0d, 0d); assertEquals(((Point) gc.getGeometryN(0)).getY(), 0d, 0d); assertEquals(((Point) gc.getGeometryN(1)).getX(), 1d, 0d); assertEquals(((Point) gc.getGeometryN(1)).getY(), 1d, 0d); }
List<Integer> commands(Geometry geometry) { x = 0; y = 0; if (geometry instanceof Polygon) { Polygon polygon = (Polygon) geometry; if (polygon.getNumInteriorRing() > 0) { List<Integer> commands = new ArrayList<Integer>(); commands.addAll(commands(polygon.getExteriorRing().getCoordinates(), true)); for (int i = 0; i < polygon.getNumInteriorRing(); i++) { commands.addAll(commands(polygon.getInteriorRingN(i).getCoordinates(), true)); } return commands; } } if (geometry instanceof MultiLineString || geometry instanceof MultiPoint) { List<Integer> commands = new ArrayList<Integer>(); GeometryCollection gc = (GeometryCollection) geometry; for (int i = 0; i < gc.getNumGeometries(); i++) { commands.addAll(commands(gc.getGeometryN(i).getCoordinates(), false)); } return commands; } return commands(geometry.getCoordinates(), shouldClosePath(geometry)); }
private static void transformGeometry(Geometry geometry) { if (geometry == null) { return; } if (geometry instanceof GeometryCollection) { GeometryCollection collection = (GeometryCollection) geometry; for (int i = 0; i < collection.getNumGeometries(); i++) { transformGeometry(collection.getGeometryN(i)); } } else if (geometry instanceof Polygon) { Polygon polygon = (Polygon) geometry; transformGeometry(polygon.getExteriorRing()); for (int i = 0; i < polygon.getNumInteriorRing(); i++) { transformGeometry(polygon.getInteriorRingN(i)); } } else if (geometry instanceof LineString) { LiteCoordinateSequence seq = (LiteCoordinateSequence) ((LineString) geometry).getCoordinateSequence(); double[] coords = seq.getArray(); for (int i = 0; i < coords.length; i++) { coords[i] = (int) (coords[i] + 0.5d); } seq.setArray(coords); } }
/** * Extract the coordinate arrays for a geometry into a List. * * @param g the Geometry to extract from * @param coordArrayList the List to add the coordinate arrays to * @param orientPolygons whether or not the arrays in the List should be oriented (clockwise for * the shell, counterclockwise for the holes) */ public static void addCoordinateArrays(Geometry g, boolean orientPolygons, List coordArrayList) { if (g.getDimension() <= 0) { return; } else if (g instanceof LineString) { LineString l = (LineString) g; coordArrayList.add(l.getCoordinates()); } else if (g instanceof Polygon) { Polygon poly = (Polygon) g; Coordinate[] shell = poly.getExteriorRing().getCoordinates(); if (orientPolygons) { shell = ensureOrientation(shell, CGAlgorithms.CLOCKWISE); } coordArrayList.add(shell); for (int i = 0; i < poly.getNumInteriorRing(); i++) { Coordinate[] hole = poly.getInteriorRingN(i).getCoordinates(); if (orientPolygons) { hole = ensureOrientation(hole, CGAlgorithms.COUNTERCLOCKWISE); } coordArrayList.add(hole); } } else if (g instanceof GeometryCollection) { GeometryCollection gc = (GeometryCollection) g; for (int i = 0; i < gc.getNumGeometries(); i++) { addCoordinateArrays(gc.getGeometryN(i), orientPolygons, coordArrayList); } } else { Assert.shouldNeverReachHere("Geometry of type " + g.getClass().getName() + " not handled"); } }
public final void decimateTransformGeneralize(Geometry geometry, MathTransform transform) throws TransformException { if (geometry instanceof GeometryCollection) { GeometryCollection collection = (GeometryCollection) geometry; final int length = collection.getNumGeometries(); for (int i = 0; i < length; i++) { decimateTransformGeneralize(collection.getGeometryN(i), transform); } } else if (geometry instanceof Point) { LiteCoordinateSequence seq = (LiteCoordinateSequence) ((Point) geometry).getCoordinateSequence(); decimateTransformGeneralize(seq, transform); } else if (geometry instanceof Polygon) { Polygon polygon = (Polygon) geometry; decimateTransformGeneralize(polygon.getExteriorRing(), transform); final int length = polygon.getNumInteriorRing(); for (int i = 0; i < length; i++) { decimateTransformGeneralize(polygon.getInteriorRingN(i), transform); } } else if (geometry instanceof LineString) { LiteCoordinateSequence seq = (LiteCoordinateSequence) ((LineString) geometry).getCoordinateSequence(); decimateTransformGeneralize(seq, transform); } }
private void splitAndAddFeatures( String layerName, Map<String, ?> attributes, GeometryCollection geometry) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Geometry subGeometry = geometry.getGeometryN(i); addFeature(layerName, attributes, subGeometry); } }
protected static Geometry transformGeometryCollection( CoordinateTransform ct, GeometryCollection geometryCollection) throws Exception { Geometry[] geometry = new Geometry[geometryCollection.getNumGeometries()]; for (int i = 0; i < geometry.length; ++i) { geometry[i] = transformGeometry(ct, geometryCollection.getGeometryN(i)); } return geometryCollection.getFactory().createGeometryCollection(geometry); }
private void validate(final Geometry geom, final List<ValidationResult> validationErrors) { if (geom.isEmpty()) { return; } if (geom instanceof GeometryCollection) { final GeometryCollection gc = (GeometryCollection) geom; for (int numGeom = 0; numGeom < gc.getNumGeometries(); numGeom++) { validate(gc.getGeometryN(numGeom), validationErrors); } } final ValidationResult result = new ValidationResult(); result.setWkt(geom.toText()); final List<String> messages = new ArrayList<String>(); if (!geom.isValid()) { messages.add("Error en topología básica"); } if (!geom.isSimple()) { messages.add("No es una geometría simple"); } if (repeatedPointTester.hasRepeatedPoint(geom)) { messages.add("Se encuentran vértices repetidos"); } if (geom instanceof Polygon) { final Polygon polygon = (Polygon) geom; if (CGAlgorithms.isCCW(polygon.getExteriorRing().getCoordinates())) { messages.add("Error en orientación del polígono"); } else { for (int numRing = 0; numRing < polygon.getNumInteriorRing(); numRing++) { if (!CGAlgorithms.isCCW(polygon.getInteriorRingN(numRing).getCoordinates())) { messages.add("Error en orientación del polígono en anillos interiores"); break; } } } if (!validateMinPolygonArea(geom)) { messages.add("Error en validación mínima de area de un polígono"); } } if (!validateMinSegmentLength(geom)) { messages.add("Error en validación mínima de longitud de segmento"); } if (!messages.isEmpty()) { result.setMessages(messages); validationErrors.add(result); } }
private JSONBuilder writeGeomCollection(GeometryCollection collection) { this.key("geometries"); this.array(); for (int i = 0, n = collection.getNumGeometries(); i < n; i++) { writeGeom(collection.getGeometryN(i)); } return this.endArray(); }
public void testHeterogeneous() throws Exception { Node node = createNode( gcol, new ElementInstance[] {point1, point2, line1, ring1, poly1}, new Object[] { gf.createPoint(new Coordinate(0, 0)), gf.createPoint(new Coordinate(1, 1)), gf.createLineString(new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 1)}), gf.createLinearRing( new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(0, 0) }), gf.createPolygon( gf.createLinearRing( new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(0, 0) }), null) }, null, null); GMLGeometryCollectionTypeBinding s = (GMLGeometryCollectionTypeBinding) container.getComponentInstanceOfType(GMLGeometryCollectionTypeBinding.class); GeometryCollection gc = (GeometryCollection) s.parse(gcol, node, null); assertNotNull(gc); assertEquals(gc.getNumGeometries(), 5); assertTrue(gc.getGeometryN(0) instanceof Point); assertTrue(gc.getGeometryN(1) instanceof Point); assertTrue(gc.getGeometryN(2) instanceof LineString); assertTrue(gc.getGeometryN(3) instanceof LinearRing); assertTrue(gc.getGeometryN(4) instanceof Polygon); }
protected <T> void accumulateGeometries( List<T> collection, Geometry g, Class<? extends T> target) { if (target.isInstance(g)) { collection.add((T) g); } else if (g instanceof GeometryCollection) { GeometryCollection coll = (GeometryCollection) g; for (int i = 0; i < coll.getNumGeometries(); i++) { accumulateGeometries(collection, coll.getGeometryN(i), target); } } }
Map<String, Object> createGeometryCollection(GeometryCollection gcol) { LinkedHashMap obj = new LinkedHashMap(); ArrayList geoms = new ArrayList(gcol.getNumGeometries()); for (int i = 0; i < gcol.getNumGeometries(); i++) { geoms.add(create(gcol.getGeometryN(i))); } obj.put("type", "GeometryCollection"); obj.put("geometries", geoms); return obj; }
protected Geometry transformGeometryCollection(GeometryCollection geom, Geometry parent) { List transGeomList = new ArrayList(); for (int i = 0; i < geom.getNumGeometries(); i++) { Geometry transformGeom = transform(geom.getGeometryN(i)); if (transformGeom == null) continue; if (pruneEmptyGeometry && transformGeom.isEmpty()) continue; transGeomList.add(transformGeom); } if (preserveGeometryCollectionType) return factory.createGeometryCollection(GeometryFactory.toGeometryArray(transGeomList)); return factory.buildGeometry(transGeomList); }
/** decimates JTS geometries. */ public final Geometry decimate(Geometry geom) { GeometryFactory gFac = new GeometryFactory(geom.getPrecisionModel(), geom.getSRID()); if (spanx == -1) return geom; if (geom instanceof MultiPoint) { // TODO check geometry and if its bbox is too small turn it into a 1 // point geom return geom; } if (geom instanceof GeometryCollection) { // TODO check geometry and if its bbox is too small turn it into a // 1-2 point geom // takes a bit of work because the geometry will need to be // recreated. GeometryCollection collection = (GeometryCollection) geom; Geometry[] result = new Geometry[collection.getDimension()]; final int numGeometries = collection.getNumGeometries(); for (int i = 0; i < numGeometries; i++) { result[i] = decimate(collection.getGeometryN(i)); } return gFac.createGeometryCollection(result); } else if (geom instanceof LineString) { LineString line = (LineString) geom; CoordinateSequence seq = (CoordinateSequence) line.getCoordinateSequence(); LiteCoordinateSequence lseq = new LiteCoordinateSequence(seq.toCoordinateArray()); if (decimateOnEnvelope(line, lseq)) { if (lseq.size() >= 2) return gFac.createLineString(lseq); } if (lseq.size() >= 2) return gFac.createLineString(decimate(lseq)); return null; } else if (geom instanceof Polygon) { Polygon line = (Polygon) geom; Coordinate[] exterior = decimate(line.getExteriorRing()).getCoordinates(); forceClosed(exterior); if (exterior.length > 3) { LinearRing ring = gFac.createLinearRing(exterior); final int numRings = line.getNumInteriorRing(); List<LinearRing> rings = new ArrayList<LinearRing>(); for (int i = 0; i < numRings; i++) { Coordinate[] interior = decimate(line.getInteriorRingN(i)).getCoordinates(); forceClosed(interior); if (interior.length > 3) rings.add(gFac.createLinearRing(interior)); } return gFac.createPolygon(ring, rings.toArray(new LinearRing[] {})); } return null; } return geom; }
/** * The method explodes a geometry, if it is a multi-geometry (Geometry Collection), into their * parts. * * @param geom * @return a list of geometries */ public static ArrayList<Geometry> explodeGeomsIfMultiG(Geometry geom) { ArrayList<Geometry> geoms = new ArrayList<Geometry>(); if (geom instanceof GeometryCollection) { // System.out.println("explode multigeoms"); GeometryCollection multig = (GeometryCollection) geom; for (int i = 0; i < multig.getNumGeometries(); i++) { Geometry g = (Geometry) multig.getGeometryN(i); geoms.add(g); } } else { geoms.add(geom); } return geoms; }
List toList(GeometryCollection mgeom) { ArrayList list = new ArrayList(mgeom.getNumGeometries()); for (int i = 0; i < mgeom.getNumGeometries(); i++) { Geometry g = mgeom.getGeometryN(i); if (g instanceof Polygon) { list.add(toList((Polygon) g)); } else if (g instanceof LineString) { list.add(new CoordinateSequenceEncoder(((LineString) g).getCoordinateSequence(), scale)); } else if (g instanceof Point) { list.add(new CoordinateSequenceEncoder(((Point) g).getCoordinateSequence(), scale)); } } return list; }
/** * Bulk write method for writing a collection of (hopefully) like geometries of the given * ShapeType. */ public void write(final GeometryCollection geometries, final ShapeType type) throws IOException, DataStoreException { handler = type.getShapeHandler(true); writeHeaders(geometries, type); lp = shapeBuffer.position(); for (int i = 0, ii = geometries.getNumGeometries(); i < ii; i++) { Geometry g = geometries.getGeometryN(i); writeGeometry(g); } close(); }
/** * @param geometry * @return * @throws Exception */ @Override public org.geojson.GeometryCollection buildGeoJsonGeometry(GeometryCollection geometry) throws Exception { logger.trace( ":::::::::::::::::::Called {}#buildGeoJsonGeometry for JTS_GEOMETRY : {}\n", super.toString(), geometry); org.geojson.GeometryCollection geometryCollection = new org.geojson.GeometryCollection(); for (int i = 0; i < geometry.getNumGeometries(); i++) { Geometry theGeom = geometry.getGeometryN(i); GeometryWriterImplementor implementor = GEOMETRY_WRITER_IMPLEMENTOR_STORE.getImplementorByKey(theGeom.getClass()); geometryCollection.add(implementor.buildGeoJsonGeometry(theGeom)); } return geometryCollection; }
private void writeHeaders(final GeometryCollection geometries, final ShapeType type) throws IOException { // ShapefileHeader header = new ShapefileHeader(); // Envelope bounds = geometries.getEnvelopeInternal(); // header.write(shapeBuffer, type, geometries.getNumGeometries(), // fileLength / 2, // bounds.getMinX(),bounds.getMinY(), bounds.getMaxX(),bounds.getMaxY() // ); // header.write(indexBuffer, type, geometries.getNumGeometries(), 50 + 4 // * geometries.getNumGeometries(), // bounds.getMinX(),bounds.getMinY(), bounds.getMaxX(),bounds.getMaxY() // ); int fileLength = 100; // int largestShapeSize = 0; for (int i = geometries.getNumGeometries() - 1; i >= 0; i--) { // shape length + record (2 ints) int size = handler.getLength(geometries.getGeometryN(i)) + 8; fileLength += size; // if (size > largestShapeSize) // largestShapeSize = size; } writeHeaders(geometries.getEnvelopeInternal(), type, geometries.getNumGeometries(), fileLength); }
/** * Main method - write the featurecollection to a shapefile (2d, 3d or 4d). * * @param featureCollection collection to write * @param dp 'OutputFile' or 'DefaultValue' to specify where to write, and 'ShapeType' to specify * dimentionality. */ public void write(FeatureCollection featureCollection, DriverProperties dp) throws IllegalParametersException, Exception { String shpfileName; String dbffname; String shxfname; String path; String fname; String fname_withoutextention; int shapeType; int loc; GeometryCollection gc; shpfileName = dp.getProperty(FILE_PROPERTY_KEY); if (shpfileName == null) { shpfileName = dp.getProperty(DEFAULT_VALUE_PROPERTY_KEY); } if (shpfileName == null) { throw new IllegalParametersException("no output filename specified"); } loc = shpfileName.lastIndexOf(File.separatorChar); if (loc == -1) { // loc = 0; // no path - ie. "hills.shp" // path = ""; // fname = shpfileName; // probably using the wrong path separator character. throw new Exception( "couldn't find the path separator character '" + File.separatorChar + "' in your shape file name. This you're probably using the unix (or dos) one."); } else { path = shpfileName.substring(0, loc + 1); // ie. "/data1/hills.shp" -> "/data1/" fname = shpfileName.substring(loc + 1); // ie. "/data1/hills.shp" -> "hills.shp" } loc = fname.lastIndexOf("."); if (loc == -1) { throw new IllegalParametersException("Filename must end in '.shp'"); } fname_withoutextention = fname.substring(0, loc); // ie. "hills.shp" -> "hills." dbffname = path + fname_withoutextention + ".dbf"; writeDbf(featureCollection, dbffname); // this gc will be a collection of either multi-points, multi-polygons, or multi-linestrings // polygons will have the rings in the correct order gc = makeSHAPEGeometryCollection(featureCollection); shapeType = 2; // x,y if (dp.getProperty(SHAPE_TYPE_PROPERTY_KEY) != null) { String st = dp.getProperty(SHAPE_TYPE_PROPERTY_KEY); if (st.equalsIgnoreCase("xy")) { shapeType = 2; } else if (st.equalsIgnoreCase("xym")) { shapeType = 3; } else if (st.equalsIgnoreCase("xymz")) { shapeType = 4; } else if (st.equalsIgnoreCase("xyzm")) { shapeType = 4; } else if (st.equalsIgnoreCase("xyz")) { shapeType = 4; } else { throw new IllegalParametersException( "ShapefileWriter.write() - dataproperties has a 'ShapeType' that isnt 'xy', 'xym', or 'xymz'"); } } else { if (gc.getNumGeometries() > 0) { shapeType = guessCoorinateDims(gc.getGeometryN(0)); } } URL url = new URL("file", "localhost", shpfileName); Shapefile myshape = new Shapefile(url); myshape.write(gc, shapeType); shxfname = path + fname_withoutextention + ".shx"; BufferedOutputStream in = new BufferedOutputStream(new FileOutputStream(shxfname)); EndianDataOutputStream sfile = new EndianDataOutputStream(in); myshape.writeIndex(gc, sfile, shapeType); }