static double getIntersectionArea( Geometry first, CoordinateReferenceSystem firstCRS, Geometry second, CoordinateReferenceSystem secondCRS, boolean divideFirst) { // basic checks if (firstCRS == null || secondCRS == null) throw new IllegalArgumentException("CRS cannot be set to null"); if (!Polygon.class.isAssignableFrom(first.getClass()) && !MultiPolygon.class.isAssignableFrom(first.getClass())) throw new IllegalArgumentException("first geometry must be poligonal"); if (!Polygon.class.isAssignableFrom(second.getClass()) && !MultiPolygon.class.isAssignableFrom(second.getClass())) throw new IllegalArgumentException("second geometry must be poligonal"); try { Geometry firstTargetGeometry = reprojectAndDensify(first, firstCRS, null); Geometry secondTargetGeometry = reprojectAndDensify(second, firstCRS, null); double numeratorArea = (double) (firstTargetGeometry.intersection(secondTargetGeometry)).getArea(); if (divideFirst) { double denom = firstTargetGeometry.getArea(); if (denom != 0) return numeratorArea / denom; return 0; } double denom = secondTargetGeometry.getArea(); if (denom != 0) return numeratorArea / denom; return 0; } catch (Exception e) { e.printStackTrace(); return -1; } }
/** * Ensure Line crosses the other Line at a node. * * <p> * * @param layers a HashMap of key="TypeName" value="FeatureSource" * @param envelope The bounding box of modified features * @param results Storage for the error and warning messages * @return True if no features intersect. If they do then the validation failed. * @throws Exception DOCUMENT ME! * @see org.geotools.validation.IntegrityValidation#validate(java.util.Map, * com.vividsolutions.jts.geom.Envelope, org.geotools.validation.ValidationResults) */ public boolean validate(Map layers, Envelope envelope, ValidationResults results) throws Exception { boolean r = true; FeatureSource<SimpleFeatureType, SimpleFeature> fsLine = (FeatureSource<SimpleFeatureType, SimpleFeature>) layers.get(getLineTypeRef()); FeatureCollection<SimpleFeatureType, SimpleFeature> fcLine = fsLine.getFeatures(); FeatureIterator<SimpleFeature> fLine = fcLine.features(); FeatureSource<SimpleFeatureType, SimpleFeature> fsRLine = (FeatureSource<SimpleFeatureType, SimpleFeature>) layers.get(getRestrictedLineTypeRef()); FeatureCollection<SimpleFeatureType, SimpleFeature> fcRLine = fsRLine.getFeatures(); while (fLine.hasNext()) { SimpleFeature line = fLine.next(); FeatureIterator<SimpleFeature> fRLine = fcRLine.features(); Geometry lineGeom = (Geometry) line.getDefaultGeometry(); if (envelope.contains(lineGeom.getEnvelopeInternal())) { // check for valid comparison if (LineString.class.isAssignableFrom(lineGeom.getClass())) { while (fRLine.hasNext()) { SimpleFeature rLine = fRLine.next(); Geometry rLineGeom = (Geometry) rLine.getDefaultGeometry(); if (envelope.contains(rLineGeom.getEnvelopeInternal())) { if (LineString.class.isAssignableFrom(rLineGeom.getClass())) { if (lineGeom.intersects(rLineGeom)) { if (!hasPair( ((LineString) lineGeom).getCoordinateSequence(), ((LineString) rLineGeom).getCoordinateSequence())) { results.error( rLine, "Line does not intersect line at node covered by the specified Line."); r = false; } } else { results.warning(rLine, "Does not intersect the LineString"); } // do next. } else { fcRLine.remove(rLine); results.warning( rLine, "Invalid type: this feature is not a derivative of a LineString"); } } else { fcRLine.remove(rLine); } } } else { results.warning(line, "Invalid type: this feature is not a derivative of a LineString"); } } } return r; }
private static Collection<? extends Geometry> createCompatibleGeometry( Geometry geom, Class<? extends Geometry> targetType) { Collection<Geometry> result = new ArrayList<Geometry>(); if (nonCollectionToPoint(geom, targetType, result)) return result; else if (collectionToPoint(geom, targetType, result)) return result; else if (nonCollectionToMultiPoint(geom, targetType, result)) return result; else if (collectionToMultiPoint(geom, targetType, result)) return result; else if (simpleToLine(geom, targetType, result)) return result; else if (collectionToLine(geom, targetType, result)) return result; else if (simpleToMultiLine(geom, targetType, result)) return result; else if (collectionToMultiLine(geom, targetType, result)) return result; else if (polygonToMultiLine(geom, targetType, result)) return result; else if (polygonToLine(geom, targetType, result)) return result; else if (multiPolygonToLine(geom, targetType, result)) return result; else if (multiPolygonToMultiLine(geom, targetType, result)) return result; else if (simpleToPolygon(geom, targetType, result)) return result; else if (collectionToPolygon(geom, targetType, result)) return result; else if (multiPolygonToPolygon(geom, targetType, result)) return result; else if (simpleToMultiPolygon(geom, targetType, result)) return result; else if (collectionToMultiPolygon(geom, targetType, result)) return result; else if (polygonToMultiPolygon(geom, targetType, result)) return result; else if (toLinearRing(geom, targetType, result)) return result; throw new IllegalArgumentException( "do not know how transform from " + geom.getClass().getName() + " to " + targetType.getName()); // $NON-NLS-1$ //$NON-NLS-2$ }
/** * 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"); } }
/** * Gets the internal representation for the given Geometry * * @param geometry a Geometry * @return int representation of Geometry */ public static int getGeometryType(Geometry geometry) { // LOGGER.entering("GMLUtils", "getGeometryType", geometry); if (geometry instanceof Point) { // LOGGER.finest("found point"); return POINT; } else if (geometry instanceof LineString) { // LOGGER.finest("found linestring"); return LINESTRING; } else if (geometry instanceof Polygon) { // LOGGER.finest("found polygon"); return POLYGON; } else if (geometry instanceof MultiPoint) { // LOGGER.finest("found multiPoint"); return MULTIPOINT; } else if (geometry instanceof MultiLineString) { return MULTILINESTRING; } else if (geometry instanceof MultiPolygon) { return MULTIPOLYGON; } else if (geometry instanceof GeometryCollection) { return MULTIGEOMETRY; } else { throw new IllegalArgumentException( "Unable to determine geometry type " + geometry.getClass()); } }
public static void assertEquals(Geometry s1, Geometry s2) { if (s1 instanceof LineString && s2 instanceof LineString) { assertEquals((LineString) s1, (LineString) s2); } else if (s1 instanceof Polygon && s2 instanceof Polygon) { assertEquals((Polygon) s1, (Polygon) s2); } else if (s1 instanceof MultiPoint && s2 instanceof MultiPoint) { assert s1.equals(s2) : "Expected " + s1 + " but found " + s2; } else if (s1 instanceof MultiPolygon && s2 instanceof MultiPolygon) { assertEquals((MultiPolygon) s1, (MultiPolygon) s2); } else { throw new RuntimeException( "equality of shape types not supported [" + s1.getClass().getName() + " and " + s2.getClass().getName() + "]"); } }
/** * @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; }
/** @see Transfer#nativeToJava */ @SuppressWarnings("deprecation") public Object nativeToJava(TransferData transferData) { String string = (String) TextTransfer.getInstance().nativeToJava(transferData); WKTReader reader = new WKTReader(); try { Geometry read = reader.read(string); FeatureType ft = DataUtilities.createType( "Temp Type", "*geom:" + read.getClass().getName()); // $NON-NLS-1$ //$NON-NLS-2$ return ft.create(new Object[] {read}); } catch (Exception e) { UiPlugin.log("", e); // $NON-NLS-1$ } return null; }
public final Geometry transform(Geometry inputGeom) { this.inputGeom = inputGeom; this.factory = inputGeom.getFactory(); if (inputGeom instanceof Point) return transformPoint((Point) inputGeom, null); if (inputGeom instanceof MultiPoint) return transformMultiPoint((MultiPoint) inputGeom, null); if (inputGeom instanceof LinearRing) return transformLinearRing((LinearRing) inputGeom, null); if (inputGeom instanceof LineString) return transformLineString((LineString) inputGeom, null); if (inputGeom instanceof MultiLineString) return transformMultiLineString((MultiLineString) inputGeom, null); if (inputGeom instanceof Polygon) return transformPolygon((Polygon) inputGeom, null); if (inputGeom instanceof MultiPolygon) return transformMultiPolygon((MultiPolygon) inputGeom, null); if (inputGeom instanceof GeometryCollection) return transformGeometryCollection((GeometryCollection) inputGeom, null); throw new IllegalArgumentException( "Unknown Geometry subtype: " + inputGeom.getClass().getName()); }
public static String getGeometryName(Geometry geometry) { if (geometry instanceof Point) { return "Point"; } else if (geometry instanceof LineString) { return "LineString"; } else if (geometry instanceof Polygon) { return "Polygon"; } else if (geometry instanceof MultiPoint) { return "MultiPoint"; } else if (geometry instanceof MultiLineString) { return "MultiLineString"; } else if (geometry instanceof MultiPolygon) { return "MultiPolygon"; } else if (geometry instanceof GeometryCollection) { return "GeometryCollection"; } else { throw new IllegalArgumentException("Unknown geometry type " + geometry.getClass()); } }
public static int getWKBType(Geometry geom) { // We always write emtpy geometries as emtpy collections - for OpenGIS // conformance if (geom.isEmpty()) { return org.postgis.Geometry.GEOMETRYCOLLECTION; } else if (geom instanceof Point) { return org.postgis.Geometry.POINT; } else if (geom instanceof com.vividsolutions.jts.geom.LineString) { return org.postgis.Geometry.LINESTRING; } else if (geom instanceof com.vividsolutions.jts.geom.Polygon) { return org.postgis.Geometry.POLYGON; } else if (geom instanceof MultiPoint) { return org.postgis.Geometry.MULTIPOINT; } else if (geom instanceof MultiLineString) { return org.postgis.Geometry.MULTILINESTRING; } else if (geom instanceof com.vividsolutions.jts.geom.MultiPolygon) { return org.postgis.Geometry.MULTIPOLYGON; } if (geom instanceof com.vividsolutions.jts.geom.GeometryCollection) { return org.postgis.Geometry.GEOMETRYCOLLECTION; } else { throw new IllegalArgumentException("Unknown Geometry Type: " + geom.getClass().getName()); } }
/** * Add a feature with layer name (typically feature type name), some attributes and a Geometry. * The Geometry must be in "pixel" space 0,0 lower left and 256,256 upper right. * * <p>For optimization, geometries will be clipped, geometries will simplified and features with * geometries outside of the tile will be skipped. * * @param layerName * @param attributes * @param geometry */ public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry) { // split up MultiPolygon and GeometryCollection (without subclasses) if (geometry instanceof MultiPolygon || geometry.getClass().equals(GeometryCollection.class)) { splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry); return; } // skip small Polygon/LineString. if (geometry instanceof Polygon && geometry.getArea() < 1.0d) { return; } if (geometry instanceof LineString && geometry.getLength() < 1.0d) { return; } // clip geometry. polygons right outside. other geometries at tile // border. try { if (geometry instanceof Polygon) { Geometry original = geometry; geometry = polygonClipGeometry.intersection(original); // some times a intersection is returned as an empty geometry. // going via wkt fixes the problem. if (geometry.isEmpty() && original.intersects(polygonClipGeometry)) { Geometry originalViaWkt = new WKTReader().read(original.toText()); geometry = polygonClipGeometry.intersection(originalViaWkt); } } else { geometry = clipGeometry.intersection(geometry); } } catch (TopologyException e) { // could not intersect. original geometry will be used instead. } catch (ParseException e1) { // could not encode/decode WKT. original geometry will be used instead. } // if clipping result in MultiPolygon, then split once more if (geometry instanceof MultiPolygon) { splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry); return; } // no need to add empty geometry if (geometry.isEmpty()) { return; } Layer layer = layers.get(layerName); if (layer == null) { layer = new Layer(); layers.put(layerName, layer); } Feature feature = new Feature(); feature.geometry = geometry; for (Map.Entry<String, ?> e : attributes.entrySet()) { // skip attribute without value if (e.getValue() == null) { continue; } feature.tags.add(layer.key(e.getKey())); feature.tags.add(layer.value(e.getValue())); } layer.features.add(feature); }
private void drawGeometry( Geometry geometry, java.awt.geom.Rectangle2D.Double bounds, Graphics graphics, int width, int height, int flags) { Coordinate[] coords = geometry.getCoordinates(); double xInterval = bounds.width / (double) width; double yInterval = bounds.height / (double) height; // System.out.println("xInterval: " + xInterval + " yInterval: " + yInterval); if (xInterval > yInterval) { yInterval = xInterval; } if (yInterval > xInterval) { xInterval = yInterval; } // for later double cellsize = yInterval; // TODO fix this stupid legacy preallocation when it works int[] coordGridX = new int[coords.length]; int[] coordGridY = new int[coords.length]; // Go through coordinate array in order received (clockwise) for (int n = 0; n < coords.length; n++) { coordGridX[n] = (int) (((coords[n].x - bounds.x) / xInterval)); coordGridY[n] = (int) (((coords[n].y - bounds.y) / yInterval)); coordGridY[n] = height - coordGridY[n] - 1; // this may happen at the extremes, unless we use the pixel center as the coordinate if (coordGridX[n] < 0) coordGridX[n] = 0; if (coordGridY[n] < 0) coordGridY[n] = 0; if (coordGridX[n] >= width) coordGridX[n] = width - 1; if (coordGridY[n] >= height) coordGridY[n] = height - 1; } /* * ok, this if isn't really necessary, but it may become so in the * future. */ if (geometry.getClass().equals(com.vividsolutions.jts.geom.Polygon.class)) { if ((flags & FILLED_SHAPES) != 0) { graphics.fillPolygon(coordGridX, coordGridY, coords.length); } else { graphics.drawPolyline(coordGridX, coordGridY, coords.length); } } else if (geometry.getClass().equals(LinearRing.class)) { graphics.drawPolyline(coordGridX, coordGridY, coords.length); } else if (geometry.getClass().equals(LineString.class)) { graphics.drawPolyline(coordGridX, coordGridY, coords.length); } else if (geometry.getClass().equals(Point.class)) { graphics.drawPolyline(coordGridX, coordGridY, coords.length); } }
/** * Return an image of the world with a shape drawn on it. Flags control the rendering mode. * Default is a hollow shape in red outline, touching the borders of the image. * * @param shape * @param width * @param height * @param flags * @return * @throws ThinklabException */ public BufferedImage getImagery( Envelope envelope, ShapeValue shape, int width, int height, int flags) throws ThinklabException { BufferedImage ret = getImagery(envelope, width, height); GeometryFactory geoFactory = new GeometryFactory(); double edgeBuffer = 0.0; if (ret == null) { ret = getSatelliteImage( envelope, width, height, null, null, HAlignment.MIDDLE, VAlignment.MIDDLE); } /* * draw shape boundaries. */ Geometry geometry = shape.getGeometry(); double x = envelope.getMinX() - edgeBuffer; double y = envelope.getMinY() - edgeBuffer; double w = envelope.getWidth() + edgeBuffer * 2; double h = envelope.getHeight() + edgeBuffer * 2; java.awt.geom.Rectangle2D.Double bounds = new java.awt.geom.Rectangle2D.Double(x, y, w, h); Graphics graphics = ret.getGraphics(); if ((flags & GREEN_SHAPES) != 0) { graphics.setColor(Color.green); } else { graphics.setColor(Color.red); } graphics.setPaintMode(); if (geometry.getClass().equals(MultiPolygon.class) || geometry.getClass().equals(Polygon.class)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { com.vividsolutions.jts.geom.Polygon poly = (com.vividsolutions.jts.geom.Polygon) geometry.getGeometryN(i); LinearRing lr = geoFactory.createLinearRing(poly.getExteriorRing().getCoordinates()); com.vividsolutions.jts.geom.Polygon part = geoFactory.createPolygon(lr, null); drawGeometry(part, bounds, graphics, width, height, flags); for (int j = 0; j < poly.getNumInteriorRing(); j++) { lr = geoFactory.createLinearRing(poly.getInteriorRingN(j).getCoordinates()); part = geoFactory.createPolygon(lr, null); drawGeometry(part, bounds, graphics, width, height, flags); } } } else if (geometry.getClass().equals(MultiLineString.class)) { MultiLineString mp = (MultiLineString) geometry; for (int n = 0; n < mp.getNumGeometries(); n++) { drawGeometry(mp.getGeometryN(n), bounds, graphics, width, height, flags); } } else if (geometry.getClass().equals(MultiPoint.class)) { MultiPoint mp = (MultiPoint) geometry; for (int n = 0; n < mp.getNumGeometries(); n++) { drawGeometry(mp.getGeometryN(n), bounds, graphics, width, height, flags); } } else { drawGeometry(geometry, bounds, graphics, width, height, flags); } return ret; }
/** * SAX handler - handle state information and transitions based on ending elements. * * @param uri Description of the Parameter * @param name Description of the Parameter * @param qName Description of the Parameter * @exception SAXException Description of the Exception */ @SuppressWarnings({"unused", "unchecked"}) public void endElement(String uri, String name, String qName) throws SAXException { // System.out.println("/" + name); // System.out.println("the ena name="+name); if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty() && currGeomHandler == null && !lastEltData.isEmpty()) { // System.out.println(lastEltName + " " + lastEltData); row.addPair(lastEltName, lastEltData); } lastEltData = ""; if (name.equals("Placemark")) { placemarkactive = false; try { row.addPair(GeoTiffReader2.this.primarykey, KeyGenerator.Generate()); } catch (Exception e) { e.printStackTrace(); System.exit(0); } GeoTiffReader2.this.results.add(row); } visits.remove(name); if (currGeomHandler != null) { currGeomHandler.endElement(uri, name, qName); if (currGeomHandler.isGeometryComplete()) { Geometry g = currGeomHandler.getGeometry(); WKTWriter wkt_writer = new WKTWriter(); GMLWriter gml_writer = new GMLWriter(); if (g.getClass().equals(com.vividsolutions.jts.geom.Point.class)) { Point geometry = (com.vividsolutions.jts.geom.Point) g; row.addPair("isEmpty", geometry.isEmpty()); row.addPair("isSimple", geometry.isSimple()); row.addPair("dimension", geometry.getCoordinates().length); row.addPair("coordinateDimension", geometry.getCoordinates().length); row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension // <= // dimension // System.out.println(geometry.getCoordinate().x + " " // +geometry.getCoordinate().z); // System.out.println(geometry.get .getSRID()); // CRS. String crs = "2311"; if (crs == null) { System.err.println("No SRID specified. Aborting..."); System.exit(-1); } row.addPair( "asWKT", "<http://www.opengis.net/def/crs/EPSG/0/" + crs + ">" + wkt_writer.write(geometry)); row.addPair( "hasSerialization", "<http://www.opengis.net/def/crs/EPSG/0/" + crs + ">" + wkt_writer.write(geometry)); // newrow.addPair("hasSerialization", // wkt_writer.write(geometry)); gml_writer.setSrsName(crs); row.addPair("asGML", gml_writer.write(geometry).replaceAll("\n", " ")); row.addPair("is3D", geometry.getDimension() == 3); } else { GeometryCollection geometry = (GeometryCollection) g; row.addPair("isEmpty", geometry.isEmpty()); row.addPair("isSimple", geometry.isSimple()); row.addPair("dimension", geometry.getCoordinates().length); row.addPair("coordinateDimension", geometry.getCoordinates().length); row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension // <= // dimension // System.out.println(geometry.getCoordinate().x + " " // +geometry.getCoordinate().z); // System.out.println(geometry.get .getSRID()); // CRS. String crs = "2323"; if (crs == null) { System.err.println("No SRID specified. Aborting..."); System.exit(-1); } // geometry.getNumPoints(); // TODO spatialDimension?????? // TODO coordinateDimension?????? // Geometry geometry1= // (Geometry)sourceGeometryAttribute.getValue(); // geometry1.transform(arg0, arg1) // sourceGeometryAttribute.ge row.addPair( "asWKT", "<http://www.opengis.net/def/crs/EPSG/0/" + crs + ">" + wkt_writer.write(geometry)); row.addPair( "hasSerialization", "<http://www.opengis.net/def/crs/EPSG/0/" + crs + ">" + wkt_writer.write(geometry)); // newrow.addPair("hasSerialization", // wkt_writer.write(geometry)); gml_writer.setSrsName("http://www.opengis.net/def/crs/EPSG/0/" + crs); row.addPair("asGML", gml_writer.write(geometry).replaceAll("\n", " ")); row.addPair("is3D", geometry.getDimension() == 3); } // System.out.println(g); // System.out.println(ww.write(g)); geoms.add(g); // reset to indicate no longer parsing geometry currGeomHandler = null; } } }