/** */ public static Geometry flatten (GeometryCollection gc) { final List<Point> points = new LinkedList<Point>(); final List<LineString> lines = new LinkedList<LineString>(); final List<Polygon> polygons = new LinkedList<Polygon>(); gc.apply(new GeometryFilter() { public void filter (Geometry geom) { if (geom instanceof Point) { points.add((Point)geom); } else if (geom instanceof LineString) { lines.add((LineString)geom); } else if (geom instanceof Polygon) { polygons.add((Polygon)geom); } } }); if (!polygons.isEmpty()) { return gc.getFactory().createMultiPolygon(GeometryFactory.toPolygonArray(polygons)); } else if (!lines.isEmpty()) { return gc.getFactory().createMultiLineString(GeometryFactory.toLineStringArray(lines)); } else { return gc.getFactory().createMultiPoint(GeometryFactory.toPointArray(points)); } }
/** * check if the tile is on land * * @param top * @param left * @param bottom * @param right * @return */ public boolean checkIfTileIsOnLand(double top,double left,double bottom,double right){ boolean isOnLand=false; if(land!=null){ GeometryFactory fact = new GeometryFactory(); Coordinate[] cs=new Coordinate[5]; cs[0]=new Coordinate(top, left); cs[1]=new Coordinate(bottom, left); cs[2]=new Coordinate(top,right); cs[3]=new Coordinate(bottom,right); cs[4]=new Coordinate(top,left); Polygon tile=fact.createPolygon(cs); for (Geometry p : land) { if (p.contains(tile)) { isOnLand=true; break; } } } return isOnLand; }
/** * * @param geom * @return */ public static Geometry repair (Geometry geom) { GeometryFactory factory = geom.getFactory(); if (geom instanceof MultiPolygon) { MultiPolygon mp = (MultiPolygon)geom; Polygon[] polys = new Polygon[mp.getNumGeometries()]; for (int i = 0; i < mp.getNumGeometries(); i += 1) { polys[i] = repair((Polygon)mp.getGeometryN(i)); } return factory.createMultiPolygon(polys); } else if (geom instanceof Polygon) { return repair((Polygon)geom); } else if (geom.getGeometryType().equals("GeometryCollection")) { GeometryCollection gc = (GeometryCollection)geom; Geometry[] geoms = new Geometry[gc.getNumGeometries()]; for (int i = 0; i < gc.getNumGeometries(); i += 1) { geoms[i] = repair(gc.getGeometryN(i)); } Thread.dumpStack(); return factory.createGeometryCollection(geoms); } else { return(geom); } }
/** * * @param name * @param type * @param geoms */ public GeometryImage(String name,String type,List<Coordinate>geoms) { this.type=type; this.name=name; this.geoms=new ArrayList<>(); //attsMap=new HashMap<>(); GeometryFactory gf = new GeometryFactory(); for(Coordinate c:geoms){ AttributesGeometry att = new AttributesGeometry(new String[]{"x","y"}); att.set("x",c.x); att.set("y",c.y); Geometry gg=gf.createPoint(c); put(gg, att); } }
/** * * @param imagePosition * @param context */ public void mouseClicked(java.awt.Point imagePosition, OpenGLContext context) { if(isEditable()){ this.selectedGeometry = null; GeometryFactory gf = new GeometryFactory(); com.vividsolutions.jts.geom.Point p = gf.createPoint(new Coordinate(imagePosition.x, imagePosition.y)); for (Geometry temp : glayer.getGeometries()) { if(temp instanceof Polygon){ Coordinate[] c=DistanceOp.nearestPoints(temp, p); com.vividsolutions.jts.geom.Point nearest=gf.createPoint(c[0]); if (nearest.isWithinDistance(temp,5 * context.getZoom())) { this.selectedGeometry = temp; System.out.println(""+temp.getCoordinate().x+","+temp.getCoordinate().y); LayerPickedData.put(temp, glayer.getAttributes(temp)); break; } } } } }
public Area getShape() { Area maskArea = new Area(); Rectangle rect = new Rectangle(0, 0, reader.getWidth(), reader.getHeight()); GeometryFactory gf = new GeometryFactory(); Coordinate[] coords = new Coordinate[]{ new Coordinate((int) rect.getMinX(), (int) rect.getMinY()), new Coordinate((int) rect.getMaxX(), (int) rect.getMinY()), new Coordinate((int) rect.getMaxX(), (int) rect.getMaxY()), new Coordinate((int) rect.getMinX(), (int) rect.getMaxY()), new Coordinate((int) rect.getMinX(), (int) rect.getMinY()), }; Polygon geom = gf.createPolygon(gf.createLinearRing(coords), null); for (Geometry p : glayer.getGeometries()) { if (p.intersects(geom)) { int[] xPoints = new int[p.getNumPoints()]; int[] yPoints = new int[p.getNumPoints()]; int i = 0; for (Coordinate c : p.getCoordinates()) { xPoints[i] = (int) (c.x); yPoints[i++] = (int) (c.y); } maskArea.add(new Area(new java.awt.Polygon(xPoints, yPoints, p.getNumPoints()))); } } return maskArea; }
@BeforeClass public static void setup() { TomtomFolder tomtomFolder = mock(TomtomFolder.class); when(tomtomFolder.getFile("___a0.shp")).thenReturn("src/test/resources/tomtom/boundaries/a0/andorra______________a0.shp"); CapitalProvider capitalProvider = mock(CapitalProvider.class); Point point = new Point(new PackedCoordinateSequence.Double(new double[]{1.52185, 42.50760}, 2), new GeometryFactory()); Centroid capital = new Centroid(10560000718742L, "Capital Name", "123", 0, 1, 7, point); when(capitalProvider.get(0)).thenReturn(newArrayList(capital)); NameProvider nameProvider = mock(NameProvider.class); when(nameProvider.getAlternateNames(10200000000008L)).thenReturn(of("name", "Andorra", "name:fr", "Andorre")); OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class); when(osmLevelGenerator.getOsmLevel("andorra", 0)).thenReturn("2"); BoundariesA0Shapefile shapefile = new BoundariesA0Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator); shapefile.serialize("target/tests/"); pbfContent = read(new File("target/tests/a0.osm.pbf")); }
@BeforeClass public static void setup() { TomtomFolder tomtomFolder = mock(TomtomFolder.class); when(tomtomFolder.getFile("___a2.shp")).thenReturn("src/test/resources/tomtom/boundaries/a2/belbe2___________a2.shp"); NameProvider nameProvider = mock(NameProvider.class); when(nameProvider.getAlternateNames(10560000000838L)).thenReturn(of("name", "Leuven")); OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class); when(osmLevelGenerator.getOsmLevel("belbe2", 2)).thenReturn("6"); CapitalProvider capitalProvider = mock(CapitalProvider.class); Point point = new Point(new PackedCoordinateSequence.Double(new double[]{4.703077, 50.8756041}, 2), new GeometryFactory()); Centroid capital = new Centroid(10560000718742L, "Capital Name", "123", 2, 1, 7, point); when(capitalProvider.get(2)).thenReturn(newArrayList(capital)); BoundariesA2Shapefile shapefile = new BoundariesA2Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator); shapefile.serialize("target/tests/"); pbfContent = read(new File("target/tests/a2.osm.pbf")); }
@BeforeClass public static void setup() { TomtomFolder tomtomFolder = mock(TomtomFolder.class); when(tomtomFolder.getFile("___a1.shp")).thenReturn("src/test/resources/tomtom/boundaries/a1/belgium______________a1.shp"); NameProvider nameProvider = mock(NameProvider.class); when(nameProvider.getAlternateNames(10560000000843L)).thenReturn(of("name", "Brussel", "name:fr", "Bruxelles")); OsmLevelGenerator osmLevelGenerator = mock(OsmLevelGenerator.class); when(osmLevelGenerator.getOsmLevel("belgium", 1)).thenReturn("4"); CapitalProvider capitalProvider = mock(CapitalProvider.class); Point point = new Point(new PackedCoordinateSequence.Double(new double[]{4.868077, 50.4536041}, 2), new GeometryFactory()); Centroid capital = new Centroid(10560000718742L, "Capital Name", "123", 1, 1, 7, point); when(capitalProvider.get(1)).thenReturn(newArrayList(capital)); BoundariesA1Shapefile shapefile = new BoundariesA1Shapefile(tomtomFolder, capitalProvider, nameProvider, osmLevelGenerator); shapefile.serialize("target/tests/"); pbfContent = read(new File("target/tests/a1.osm.pbf")); }
private boolean validateMinSegmentLength(final Geometry geom, final Coordinate... coordinates) { boolean isValid = true; if (coordinates.length >= 2) { for (int i = 1; i < coordinates.length; i++) { if (!validateMinSegmentLength(coordinates[i - 1], coordinates[i])) { GeometryFactory geomFactory = new GeometryFactory(); errorCoordinates.add(geomFactory .createPoint(coordinates[i]).toText()); isValid = false; } } } return isValid; }
private static Geometry readGeometry(List<Integer> geomCmds, VectorTile.Tile.GeomType geomType, GeometryFactory geomFactory, Vec2d cursor, RingClassifier ringClassifier) { Geometry result = null; switch (geomType) { case POINT: result = readPoints(geomFactory, geomCmds, cursor); break; case LINESTRING: result = readLines(geomFactory, geomCmds, cursor); break; case POLYGON: result = readPolys(geomFactory, geomCmds, cursor, ringClassifier); break; default: LoggerFactory.getLogger(MvtReader.class) .error("readGeometry(): Unhandled geometry type [{}]", geomType); } return result; }
public static void main(String[] args) { ReedsSheppCarPlanner rsp = new ReedsSheppCarPlanner(); Coordinate footprint1 = new Coordinate(-2.0,0.5); Coordinate footprint2 = new Coordinate(2.0,0.5); Coordinate footprint3 = new Coordinate(2.0,-0.5); Coordinate footprint4 = new Coordinate(-2.0,-0.5); rsp.setRadius(0.5); rsp.setFootprint(footprint1,footprint2,footprint3,footprint4); JTSDrawingPanel panel = JTSDrawingPanel.makeEmpty("debug"); GeometryFactory gf = new GeometryFactory(); Polygon footprint = gf.createPolygon(new Coordinate[] {footprint1,footprint2,footprint3,footprint4,footprint1}); Polygon smoothedFootprint = gf.createPolygon(rsp.getCollisionCircleCenters()); System.out.println("Smoothing went from " + footprint.getCoordinates().length + " to " + smoothedFootprint.getCoordinates().length + " points"); panel.addGeometry("orig", footprint, true, true, true, "#00FF00"); panel.addGeometry("smooth", smoothedFootprint, false, false, true, "#FF0000"); for (int i = 0; i < smoothedFootprint.getCoordinates().length; i++) { double delta = 0.1; Coordinate p1 = new Coordinate(smoothedFootprint.getCoordinates()[i].x,smoothedFootprint.getCoordinates()[i].y); Coordinate p2 = new Coordinate(smoothedFootprint.getCoordinates()[i].x+delta,smoothedFootprint.getCoordinates()[i].y+delta); Coordinate p3 = new Coordinate(smoothedFootprint.getCoordinates()[i].x-delta,smoothedFootprint.getCoordinates()[i].y+delta); panel.addGeometry("_cp"+i, gf.createPolygon(new Coordinate[] {p1,p2,p3,p1}), false, false, false, "#000000"); } }
private Geometry makeObstacle(Pose p) { GeometryFactory gf = new GeometryFactory(); Geometry geom = null; if (obstacleFootprint == null) { geom = gf.createPolygon(new Coordinate[] { new Coordinate(0.0,0.0), new Coordinate(0.0,OBSTACLE_SIZE), new Coordinate(OBSTACLE_SIZE,OBSTACLE_SIZE), new Coordinate(OBSTACLE_SIZE,0.0), new Coordinate(0.0,0.0) }); } else { geom = gf.createPolygon(obstacleFootprint); } AffineTransformation at = new AffineTransformation(); at.rotate(p.getTheta()); at.translate(p.getX(), p.getY()); Geometry transGeom = at.transform(geom); Pose center = new Pose(p.getX(), p.getY(), p.getTheta()); obstacles.add(transGeom); obstacleCenters.add(center); return transGeom; }
/** * Generate a random line string under the given bounding box. * * @param geometryRand the random generator * @param minX Bounding box min x * @param maxX Bounding box max x * @param minY Bounding box min y * @param maxY Bounding box max y * @param maxLength LineString maximum length * @return A segment within this bounding box */ static Geometry getRandomGeometry(Random geometryRand, double minX, double maxX, double minY, double maxY, double maxLength) { GeometryFactory factory = new GeometryFactory(); // Create the start point Coordinate start = new Coordinate( geometryRand.nextDouble() * (maxX - minX) + minX, geometryRand.nextDouble() * (maxY - minY) + minY); // Compute an angle double angle = geometryRand.nextDouble() * Math.PI * 2; // Compute length double length = geometryRand.nextDouble() * maxLength; // Compute end point Coordinate end = new Coordinate( start.x + Math.cos(angle) * length, start.y + Math.sin(angle) * length); return factory.createLineString(new Coordinate[] { start, end }); }
private static Geometry unionTree(final List<?> tree) { final ArrayList<Geometry> geomList = new ArrayList<>(16); // Do not use Stream to conserve memory! for (final Object o : tree) { if (o instanceof List) { geomList.add(unionTree((List) o)); } else if (o instanceof Geometry) { geomList.add((Geometry) o); } if (Thread.currentThread().isInterrupted()) { throw new RuntimeException("Processing was interrupted"); } } final GeometryFactory factory = geomList.get(0).getFactory(); return factory.buildGeometry(geomList).buffer(0); }
private Geometry getShape(CSVRecord record) { if (!config.getGeographyProjection().equals("") && config.getGeographyXIndex() != -1 && config.getGeographyYIndex() != -1) { GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), Subject.SRID); Coordinate coordinate = null; Double x = Double.parseDouble(record.get(config.getGeographyXIndex())); Double y = Double.parseDouble(record.get(config.getGeographyYIndex())); if (config.getGeographyProjection().equals(CoordinateUtils.WGS84CRS)) { coordinate = new Coordinate(x, y); } else { try { coordinate = CoordinateUtils.eastNorthToLatLong(x, y, config.getGeographyProjection(), CoordinateUtils.WGS84CRS); } catch (Exception e) { log.warn("Coordinates will not be considered: " + e.getMessage()); return null; } } return geometryFactory.createPoint(coordinate); } return null; }
@Override public final Geometry edit(Geometry geometry, GeometryFactory factory) { if (geometry instanceof LinearRing) { return factory.createLinearRing(this.edit( ((LinearRing) geometry).getCoordinateSequence(), geometry)); } if (geometry instanceof LineString) { return factory.createLineString(this.edit( ((LineString) geometry).getCoordinateSequence(), geometry)); } if (geometry instanceof Point) { return factory.createPoint(this.edit( ((Point) geometry).getCoordinateSequence(), geometry)); } return geometry; }
/** * Constructeur de mesure d'orientation à partir d'une géométrie geoxygene. * @param geomGeox géométrie sur laquelle on va calculer l'orientation. * @param angleMaximum angle correspondant à la borne supérieure de l'intervalle * dans lequel doit être réalisé le calcul (valeur attendue : pi pour les polygones * et pi/2 pour les côtés des polygones). */ public MesureOrientationFeuille(IGeometry geomGeox,double angleMaximum){ listeOrientations = new ArrayList<Double> (); listePoids = new ArrayList<Double> (); try { Geometry geom=AdapterFactory.toGeometry(new GeometryFactory(), geomGeox); if (geom instanceof Polygon) { Polygon poly = (Polygon)geom; LineString contourExterieur = poly.getExteriorRing(); ajouterOrientation(contourExterieur); for (int i=0;i<poly.getNumInteriorRing();i++){ LineString contourInterieur = poly.getInteriorRingN(i); ajouterOrientation(contourInterieur); } } else { logger.error("La géométrie entrée n'est pas un polygone"); return; } } catch (Exception e) {e.printStackTrace();} this.angleMaximum = angleMaximum; nbOrientationsTestees = (int) (angleMaximum / ANGLE_PRECISION); }
@Override public <T extends IFeature> IFeatureCollection<T> loadAllFeatures(Class<T> featureClass, IGeometry geom) { Criteria criteria = session.createCriteria(featureClass); try { criteria.add( SpatialRestrictions.intersects("geom", AdapterFactory.toGeometry(new GeometryFactory(), geom))); //$NON-NLS-1$ FT_FeatureCollection<T> result = new FT_FeatureCollection<T>(); List<?> list = criteria.list(); for (Object o : list) { result.add((T) o); } return result; } catch (Exception e) { e.printStackTrace(); } return null; }
protected Geometry transformGeometryCollection(GeometryCollection geom, Geometry parent) { List transGeomList = new ArrayList(); for (int i = 0; i < geom.getNumGeometries(); i++) { Geometry transformGeom = this.transform(geom.getGeometryN(i)); if (transformGeom == null) { continue; } if (this.pruneEmptyGeometry && transformGeom.isEmpty()) { continue; } transGeomList.add(transformGeom); } if (this.preserveGeometryCollectionType) { return this.factory.createGeometryCollection(GeometryFactory.toGeometryArray(transGeomList)); } return this.factory.buildGeometry(transGeomList); }
/** * Calcul de la fermeture d'un polygone. * @param polygon polygone de départ * @param distance distance utilisée pour le buffer positif puis pour le buffer négatif * @param distanceTolerance distance utilisée pour la simplification par l'algorithme de Douglas-Peucker * @param quadrantSegments nombre de segments utilisés pour la simplification par l'algorithme de Douglas-Peucker * @param endCapStyle type d'approximation utilisée pour la simplification par l'algorithme de Douglas-Peucker * @param factory factory pour la géométrie * @return la fermeture du polygone passé en paramètre */ public static Polygon fermeture(Polygon polygon,double distance,double distanceTolerance,int quadrantSegments,int endCapStyle,GeometryFactory factory) { LinearRing exterior = (LinearRing) polygon.getExteriorRing(); Geometry boundary = factory.createPolygon(exterior, null); Polygon result = null; try{ boundary = boundary.buffer(distance,quadrantSegments,endCapStyle); boundary = boundary.buffer(-distance,quadrantSegments,endCapStyle); if (boundary.isEmpty()) return polygon; result = (Polygon)JtsAlgorithms.filtreDouglasPeucker(boundary,distanceTolerance); } catch (Exception e) { logger.error(polygon.toText()); logger.error(boundary.toText()); e.printStackTrace(); } return result; }
/** * Transforme une liste de {@link GM_Ring}s GeOxygene en {@link LinearRing}s * JTS * @param factory factory JTS * @param list liste de {@link GM_Ring}s * @return tableau de {@link LinearRing}s JTS équivalents * @throws Exception renvoie une exception si le type de géométrie n'est pas * géré. */ public static LinearRing[] toLinearRingArray(GeometryFactory factory, List<IRing> list) throws Exception { // LinearRing[] rings = new LinearRing[list.size()]; List<LinearRing> rings = new ArrayList<LinearRing>(); for (int i = 0; i < list.size(); i++) { LinearRing ring = (LinearRing) AdapterFactory.toGeometry(factory, list.get(i)); if (ring != null) { rings.add(ring); } else { return null; } } return rings.toArray(new LinearRing[0]); }
@Override public final Geometry edit(Geometry geometry, GeometryFactory factory) { if (geometry instanceof LinearRing) { return factory.createLinearRing(this.edit(geometry.getCoordinates(), geometry)); } if (geometry instanceof LineString) { return factory.createLineString(this.edit(geometry.getCoordinates(), geometry)); } if (geometry instanceof Point) { Coordinate[] newCoordinates = this.edit(geometry.getCoordinates(), geometry); return factory.createPoint((newCoordinates.length > 0) ? newCoordinates[0] : null); } return geometry; }
/** * Gets a List of {@link Polygon}s for the Voronoi cells * of this triangulation. * <p> * The userData of each polygon is set to be the {@link Coordinate} * of the cell site. This allows easily associating external * data associated with the sites to the cells. * * @param geomFact a geometry factory * @return a List of Polygons */ public List getVoronoiCellPolygons(GeometryFactory geomFact) { /* * Compute circumcentres of triangles as vertices for dual edges. * Precomputing the circumcentres is more efficient, * and more importantly ensures that the computed centres * are consistent across the Voronoi cells. */ this.visitTriangles(new TriangleCircumcentreVisitor(), true); List cells = new ArrayList(); Collection edges = this.getVertexUniqueEdges(false); for (Object edge : edges) { QuadEdge qe = (QuadEdge) edge; cells.add(this.getVoronoiCellPolygon(qe, geomFact)); } return cells; }
/** * Map user data transfer object into user entity * * @param userDTO User Data Transfer object * @return User */ public User getUserEntityFromDto(UserDTO userDTO){ User user = map(userDTO, User.class); if (userDTO.getLatitude() != null && userDTO.getLongitude() != null){ GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING)); Coordinate coordinate = new Coordinate(Double.parseDouble(userDTO.getLongitude()), Double.parseDouble(userDTO.getLatitude())); com.vividsolutions.jts.geom.Point point = gf.createPoint(coordinate); user.setLocation(point); } user.setDisplayFlag(Boolean.valueOf(userDTO.getDisplayFlag())); return user; }
/** * get a List of geometry: each geometry is an ambiguity boat * * @return List of the geometry for the ambiguity boats */ public List<Geometry> getAmbiguityboatgeometry() { List<Geometry> out = new ArrayList<Geometry>(); GeometryFactory gf = new GeometryFactory(); //loop on ambigutiy boat for (int i = 0; i < ambiguityboatlist.size(); i++) { Boat boat = ambiguityboatlist.get(i); out.add(gf.createPoint(new Coordinate(boat.getPosx(), boat.getPosy()))); } return out; }
/** * * @return */ public List<Geometry> getAllDetectedPixels() { List<Geometry> out = new ArrayList<Geometry>(); GeometryFactory gf = new GeometryFactory(); BoatPixel[] enumeration = allDetectedPixels.toArray(new BoatPixel[0]); for (BoatPixel pixel : enumeration) { out.add(gf.createPoint(new Coordinate(pixel.x, pixel.y))); } return out; }
public List<Geometry> getThresholdclipPixels() { List<Geometry> out = new ArrayList<Geometry>(); GeometryFactory gf = new GeometryFactory(); for (BoatConnectedPixelMap boat : listboatneighbours) { List<int[]> positions = boat.getThresholdclipPixels(); for (int[] position : positions) { out.add(gf.createPoint(new Coordinate(position[0], position[1]))); } } return out; }
public List<Geometry> getThresholdaggregatePixels() { List<Geometry> out = new ArrayList<Geometry>(); GeometryFactory gf = new GeometryFactory(); for (BoatConnectedPixelMap boat : listboatneighbours) { List<int[]> positions = boat.getThresholdaggregatePixels(); for (int[] position : positions) { out.add(gf.createPoint(new Coordinate(position[0], position[1]))); } } return out; }
public boolean contains(int x, int y) { GeometryFactory gf = new GeometryFactory(); Point geom = gf.createPoint(new Coordinate(x, y)); for (Geometry p : maskGeometries) { if (p.contains(geom)) { return true; } } return false; }
/** * rasterize the mask clipped with the Rectangle scaled back to full size with an offset onto a BufferedImage */ public BufferedImage rasterize(Rectangle rect, int offsetX, int offsetY, double scalingFactor) { // create the buffered image of the size of the Rectangle BufferedImage image = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_BYTE_BINARY); GeometryFactory gf = new GeometryFactory(); // define the clipping region in full scale Coordinate[] coords = new Coordinate[]{ new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))), new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))), new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))), new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))), new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),}; Polygon geom = gf.createPolygon(gf.createLinearRing(coords)); Graphics g2d = image.getGraphics(); g2d.setColor(Color.white); for (Geometry p : maskGeometries) { /*if(p instanceof MultiPolygon){ p=p.getBoundary(); }*/ if (p.intersects(geom)) { int[] xPoints = new int[p.getNumPoints()];//build array for x coordinates int[] yPoints = new int[p.getNumPoints()];//build array for y coordinates int i = 0; for (Coordinate c : p.getCoordinates()) { xPoints[i] = (int) ((c.x + offsetX ) * scalingFactor); yPoints[i] = (int) ((c.y + offsetY ) * scalingFactor); i++; } g2d.fillPolygon(xPoints, yPoints, i); } } g2d.dispose(); return image; }
/** * rasterize the mask clipped with the Rectangle scaled back to full size with an offset onto a BufferedImage */ public BufferedImage rasterizeJTS(Rectangle rect, int offsetX, int offsetY, double scalingFactor) { // create the buffered image of the size of the Rectangle BufferedImage image = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_BYTE_BINARY); GeometryFactory gf = new GeometryFactory(); // define the clipping region in full scale Coordinate[] coords = new Coordinate[]{ new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))), new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))), new Coordinate((int) (((double) rect.getMaxX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))), new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMaxY() / scalingFactor))), new Coordinate((int) (((double) rect.getMinX() / scalingFactor)), (int) (((double) rect.getMinY() / scalingFactor))),}; Polygon geom = gf.createPolygon(gf.createLinearRing(coords)); for (Geometry p : maskGeometries) { if (p.intersects(geom)) { Geometry pg=p.intersection(geom).buffer(0); //Coordinate[] coordsInter=gg.getCoordinates(); //Polygon pg=gf.createPolygon(coordsInter); for(int x=0;x<rect.width;x++){ for(int y=0;y<rect.height;y++){ Point point=gf.createPoint(new Coordinate(rect.x+x,rect.y+y)); if(pg.contains(point)){ try{ image.setRGB(x,y, Color.WHITE.getRGB()); }catch(Exception e){ logger.error(e.getMessage()+" x:"+x+" y:"+y); } } } } } } return image; }
public static List<Geometry> getTiles(int width,int height ,int xtileSize,int ytileSize) { int horTiles = width / xtileSize; int verTiles = height / ytileSize; List<Geometry> tiles = new ArrayList<Geometry>(horTiles*verTiles*8); int[] sizeTile = new int[2]; // the real size of tiles sizeTile[0] = width / horTiles; sizeTile[1] = height / verTiles; GeometryFactory geomFactory = new GeometryFactory(); Coordinate[] coo=null; for (int j = 0; j < verTiles; j++) { coo=new Coordinate[2]; coo[0]=new Coordinate(0, j * sizeTile[1]); coo[1]=new Coordinate((double)width, (double)j * sizeTile[1]); tiles.add(geomFactory.createLineString(coo)); } for (int i = 0; i < horTiles; i++) { coo=new Coordinate[2]; coo[0]=new Coordinate(i * sizeTile[0], 0); coo[1]=new Coordinate((double)i * sizeTile[0], (double)height); tiles.add(geomFactory.createLineString(coo)); } return tiles; }
/** */ public static GeometryCollection explodeMultiPolygon (MultiPolygon mp) { List<LinearRing> result = new ArrayList<LinearRing>(mp.getNumGeometries()*2); for (int i = 0; i < mp.getNumGeometries(); i += 1) { Polygon p = (Polygon)mp.getGeometryN(i); result.add((LinearRing)p.getExteriorRing()); for (int j = 0; j < p.getNumInteriorRing(); j += 1) { result.add((LinearRing)p.getInteriorRingN(j)); } } return mp.getFactory().createGeometryCollection(GeometryFactory.toGeometryArray(result)); }
/** * * @param vx * @param vy * @param width * @param height * @return */ public static Polygon createPolygon(double vx,double vy,double width,double height){ GeometryFactory gf=new GeometryFactory(); Coordinate[] vertex=new Coordinate[5]; vertex[0]=new Coordinate(vx,vy); vertex[1]=new Coordinate(vx+width,vy); vertex[2]=new Coordinate(vx+height,vy+width); vertex[3]=new Coordinate(vx,vy+height); vertex[4]=new Coordinate(vx,vy); return gf.createPolygon(vertex); }
/** * * @param timeStampStart * @param azimuth * @param pixels * @return */ public GeometryImage(String name,String type,String timeStampStart,double azimuth, Boat[] boats) { this.type=type; this.name=name; //GeometricLayer out = new GeometricLayer("point"); //setName("VDS Analysis"); geoms=new ArrayList<>(); //attsMap=new HashMap<>(); GeometryFactory gf = new GeometryFactory(); long runid = System.currentTimeMillis(); int count=0; for (Boat boat : boats) { AttributesGeometry atts = new AttributesGeometry(VDSSchema.schema);//, VDSSchema.types); atts.set(VDSSchema.ID, count++); atts.set(VDSSchema.MAXIMUM_VALUE, boat.getAllMaxValue()); atts.set(VDSSchema.TILE_AVERAGE, boat.getAllTileAvg()); atts.set(VDSSchema.TILE_STANDARD_DEVIATION, boat.getAllTileStd()); atts.set(VDSSchema.THRESHOLD, boat.getAllTrhesh()); atts.set(VDSSchema.RUN_ID, runid + ""); atts.set(VDSSchema.NUMBER_OF_AGGREGATED_PIXELS, boat.getSize()); atts.set(VDSSchema.ESTIMATED_LENGTH, boat.getLength()); atts.set(VDSSchema.ESTIMATED_WIDTH, boat.getWidth()); atts.set(VDSSchema.SIGNIFICANCE, boat.getAllSignificance());//(boat.getLength() - boat.getWidth()) / (boat.getWidth() * boat.getHeading())); timeStampStart=timeStampStart.replace("Z", ""); atts.set(VDSSchema.DATE, Timestamp.valueOf(timeStampStart)); atts.set(VDSSchema.VS, 0); //compute the direction of the vessel considering the azimuth of the image result is between 0 and 180 degree double degree = boat.getHeading() + 90 + azimuth; if (degree > 180) { degree = degree - 180; } degree = degree-90; atts.set(VDSSchema.ESTIMATED_HEADING, degree); Point p=gf.createPoint(new Coordinate(boat.getPosx(), boat.getPosy())); p.setUserData(atts); put(p); } }
public boolean contains(int x, int y) { if (getType().equals(GeometryImage.POINT)) { return false; } GeometryFactory gf = new GeometryFactory(); Point geom = gf.createPoint(new Coordinate(x, y)); for (Geometry p : glayer.getGeometries()) { if (p.contains(geom)) { return true; } } return false; }
public Area getShape(int width, int height) { Area maskArea = new Area(); Rectangle rect = new Rectangle(0, 0, width,height);//reader.getWidth(), reader.getHeight()); GeometryFactory gf = new GeometryFactory(); Coordinate[] coords = new Coordinate[]{ new Coordinate((int) rect.getMinX(), (int) rect.getMinY()), new Coordinate((int) rect.getMaxX(), (int) rect.getMinY()), new Coordinate((int) rect.getMaxX(), (int) rect.getMaxY()), new Coordinate((int) rect.getMinX(), (int) rect.getMaxY()), new Coordinate((int) rect.getMinX(), (int) rect.getMinY()),}; Polygon geom = gf.createPolygon(gf.createLinearRing(coords), null); for (Geometry p : glayer.getGeometries()) { if (p.intersects(geom)) { int[] xPoints = new int[p.getNumPoints()]; int[] yPoints = new int[p.getNumPoints()]; int i = 0; for (Coordinate c : p.getCoordinates()) { xPoints[i] = (int) (c.x); yPoints[i++] = (int) (c.y); } maskArea.add(new Area(new java.awt.Polygon(xPoints, yPoints, p.getNumPoints()))); } } return maskArea; }
/** * * @param imagePosition * @param context */ public void mouseClicked(java.awt.Point imagePosition,Object glContext) { OpenGLContext context=(OpenGLContext)glContext; this.selectedGeometry = null; GeometryFactory gf = new GeometryFactory(); com.vividsolutions.jts.geom.Point p = gf.createPoint(new Coordinate(imagePosition.x, imagePosition.y)); for (Geometry temp : glayer.getGeometries()) { //if (p.equalsExact(temp, 5 * context.getZoom())) { if (p.equalsExact(temp, 5 * context.getZoom())) { this.selectedGeometry = temp; //System.out.println(""+temp.getCoordinate().x+","+temp.getCoordinate().y); LayerPickedData.put(temp, glayer.getAttributes(temp)); } } }
public void mouseClicked(java.awt.Point imagePosition, int button,Object graphicContext) { OpenGLContext context=(OpenGLContext)graphicContext; this.selectedGeometry = null; GeometryFactory gf = new GeometryFactory(); Point p = gf.createPoint(new Coordinate(imagePosition.x, imagePosition.y)); for (Point temp : interpolated) { if (temp.isWithinDistance(p, 5 * context.getZoom())) { this.selectedGeometry = temp; LayerPickedData.put(temp, glayer.getAttributes(temp)); } } }