/** */ 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)); } }
/** * * @param xs * @return * @throws ParseException */ public static Polygon createPolygon(double[]...xs) throws ParseException{ StringBuilder builder =new StringBuilder("POLYGON(("); for(int i=0;i<xs.length;i++){ double x[]=xs[i]; if(i<(xs.length-1)) builder=builder.append(x[0]).append(" ").append(x[1]).append(","); else builder=builder.append(x[0]).append(" ").append(x[1]).append("))"); } Polygon imageP = (Polygon) new WKTReader().read(builder.toString()); /*Coordinate[]cs=new Coordinate[xs.length]; for(int i=0;i<xs.length;i++){ cs[i]=new Coordinate(xs[i][0],xs[i][1]); } GeometryFactory factor=new GeometryFactory(); Polygon imageP=factor.createPolygon(cs);*/ return imageP; }
/** * * @param args */ private GeometryImage loadShapeFile(File file,String name){//String[] args) { GeometryImage gl=null; ImageLayer imgLayer=LayerManager.getIstanceManager().getCurrentImageLayer(); if(imgLayer!=null){ try { Polygon imageP=((SarImageReader)imgLayer.getImageReader()).getBbox(PlatformConfiguration.getConfigurationInstance().getLandMaskMargin(0)); long start=System.currentTimeMillis(); gl = SimpleShapefile.createIntersectedLayer(file,imageP,((SarImageReader)imgLayer.getImageReader()).getGeoTransform()); long end=System.currentTimeMillis(); System.out.println("Shapefile loaded in:"+(end-start)); // if 5 args, set a specific name if (name!=null&&!name.equals("")) { if (gl != null) { gl.setName(name); } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } return gl; }
/** * * @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 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; }
@Test public void should_split_polygon_in_16() { Polygon polygon = polygon( new Coordinate(0.0, 0.0), new Coordinate(1.0, 0.0), new Coordinate(1.0, 1.0), new Coordinate(0.0, 1.0), new Coordinate(0.0, 0.0)); List<Geometry> geoms = LargePolygonSplitter.split(polygon, 0.1); assertThat(geoms).extracting(Geometry::toString).hasSize(16).contains( "POLYGON ((0.25 0, 0 0, 0 0.25, 0.25 0.25, 0.25 0))", "POLYGON ((0 0.25, 0 0.5, 0.25 0.5, 0.25 0.25, 0 0.25))", "POLYGON ((0.25 0.5, 0.5 0.5, 0.5 0.25, 0.25 0.25, 0.25 0.5))"); }
private static void checkSearchRadius(Geometry geom, double value) throws Exception { if (geom instanceof Point) { if (LocationsServiceSettings.getMaximumSearchRadiusForPoints() > 0 && LocationsServiceSettings.getMaximumSearchRadiusForPoints() < value) throw new ParameterOutOfRangeException(LocationsErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "radius", Double.toString(value), Double.toString(LocationsServiceSettings.getMaximumSearchRadiusForPoints())); } else if (geom instanceof LineString) { if (LocationsServiceSettings.getMaximumSearchRadiusForLinestrings() > 0 && LocationsServiceSettings.getMaximumSearchRadiusForLinestrings() < value) throw new ParameterOutOfRangeException(LocationsErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "radius", Double.toString(value), Double.toString(LocationsServiceSettings.getMaximumSearchRadiusForLinestrings())); } else if (geom instanceof Polygon) { if (LocationsServiceSettings.getMaximumSearchRadiusForPolygons() > 0 && LocationsServiceSettings.getMaximumSearchRadiusForPolygons() < value) throw new ParameterOutOfRangeException(LocationsErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "radius", Double.toString(value), Double.toString(LocationsServiceSettings.getMaximumSearchRadiusForPolygons())); } }
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"); } }
/** * Removes collinear vertices from the provided {@link Geometry}. * * <p> * For the moment this implementation only accepts, {@link Polygon}, {@link LineString} and {@link MultiPolygon} It will throw an exception if the * geometry is not one of those types * * @param g the instance of a {@link Geometry} to remove collinear vertices from. * @return a new instance of the provided {@link Geometry} without collinear vertices. */ public static Geometry removeCollinearVertices(final Geometry g) { if (g == null) { throw new NullPointerException("The provided Geometry is null"); } if (g instanceof LineString) { return removeCollinearVertices((LineString) g); } else if (g instanceof Polygon) { return removeCollinearVertices((Polygon) g); } else if (g instanceof MultiPolygon) { MultiPolygon mp = (MultiPolygon) g; Polygon[] parts = new Polygon[mp.getNumGeometries()]; for (int i = 0; i < mp.getNumGeometries(); i++) { Polygon part = (Polygon) mp.getGeometryN(i); part = removeCollinearVertices(part); parts[i] = part; } return g.getFactory().createMultiPolygon(parts); } throw new IllegalArgumentException( "This method can work on LineString, Polygon and Multipolygon: " + g.getClass()); }
/** * * @param polygons * @return */ public static List<Geometry> mergePolygons(List<Geometry> polygons) { boolean done; do { done = true; for (int i = 0; i < polygons.size(); i++) { Geometry a = polygons.get(i); for (int j = i + 1; j < polygons.size();) { final Geometry b = polygons.get(j); if (a.intersects(b)) { polygons.set(i, (Polygon) a.union(b)); a = polygons.get(i); polygons.remove(j); done = false; } else { j++; } } } } while (!done); return polygons; }
public void testParsePolygonNoHoles() throws IOException { XContentBuilder polygonGeoJson = XContentFactory.jsonBuilder() .startObject() .field("type", "Polygon") .startArray("coordinates") .startArray() .startArray().value(100.0).value(1.0).endArray() .startArray().value(101.0).value(1.0).endArray() .startArray().value(101.0).value(0.0).endArray() .startArray().value(100.0).value(0.0).endArray() .startArray().value(100.0).value(1.0).endArray() .endArray() .endArray() .endObject(); List<Coordinate> shellCoordinates = new ArrayList<>(); shellCoordinates.add(new Coordinate(100, 0)); shellCoordinates.add(new Coordinate(101, 0)); shellCoordinates.add(new Coordinate(101, 1)); shellCoordinates.add(new Coordinate(100, 1)); shellCoordinates.add(new Coordinate(100, 0)); LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, null); assertGeometryEquals(jtsGeom(expected), polygonGeoJson); }
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.assertEquals(s1, s2); } else if (s1 instanceof MultiPolygon && s2 instanceof MultiPolygon) { assertEquals((MultiPolygon) s1, (MultiPolygon) s2); } else if (s1 instanceof MultiLineString && s2 instanceof MultiLineString) { assertEquals((MultiLineString) s1, (MultiLineString) s2); } else { throw new RuntimeException("equality of shape types not supported [" + s1.getClass().getName() + " and " + s2.getClass().getName() + "]"); } }
@Override public void streamStreetSegments( IWayGraphOutputFormat<T> outputFormat, Polygon bounds, String graphName, String version) throws WaySegmentSerializationException, GraphNotExistsException { // TODO: Hier sollen die View-Metadaten und dann die Graph-Metadaten gelesen werden! // Daher müssen hier je nach View-Filter die Metadaten generiert werden. Zudem muss im Metadaten-Objekt der // Original-Graphname und -Version mit dem zugrunde liegenden Graphen belegt werden! IWayGraphVersionMetadata metadata = metadataService.getWayGraphVersionMetadata(graphName, version); outputFormat.serialize(metadata); // graphReadService.streamStreetSegments(outputFormat.getSegmentOutputFormat(), bounds, graphName, version); graphReadService.streamStreetSegments(outputFormat, bounds, graphName, version); outputFormat.close(); }
@Test public void should_split_polygon_in_4() { Polygon polygon = polygon( new Coordinate(0.0, 0.0), new Coordinate(1.0, 0.0), new Coordinate(1.0, 1.0), new Coordinate(0.0, 1.0), new Coordinate(0.0, 0.0)); List<Geometry> geoms = LargePolygonSplitter.split(polygon, 0.4); assertThat(geoms).extracting(Geometry::toString).containsExactly( "POLYGON ((0.5 0, 0 0, 0 0.5, 0.5 0.5, 0.5 0))", "POLYGON ((0 1, 0.5 1, 0.5 0.5, 0 0.5, 0 1))", "POLYGON ((1 1, 1 0.5, 0.5 0.5, 0.5 1, 1 1))", "POLYGON ((1 0, 0.5 0, 0.5 0.5, 1 0.5, 1 0))"); }
private void addIsochrone(IsochroneMap isochroneMap, GeometryCollection points, double isoValue, double maxRadius) { if (points.isEmpty()) return; ConcaveHull ch = new ConcaveHull(points, getConcaveHullTreshold(isoValue), false); Geometry geom = ch.getConcaveHull(); if (geom instanceof GeometryCollection) { GeometryCollection geomColl = (GeometryCollection)geom; if (geomColl.isEmpty()) return; } Polygon poly = (Polygon)geom; copyConvexHullPoints(poly); isochroneMap.addIsochrone(new Isochrone(poly, isoValue, maxRadius)); }
protected void updateCompletedMetadata(IWayGraphVersionMetadata savedMetadata, int connectionsCount, Polygon coveredArea, int segmentsCount, String segmentType) { savedMetadata.setConnectionsCount(connectionsCount); savedMetadata.setCoveredArea(coveredArea); savedMetadata.setSegmentsCount(segmentsCount); if(savedMetadata.getType() == null || !savedMetadata.getType().equals(segmentType)) { log.info("different segment type in metadata then present based on deserialisation," + " replacing metadata value with present value: " + segmentType); savedMetadata.setType(segmentType); } metadataDao.updateGraphVersion(savedMetadata); // post processing of stored graph. e.g. add check constraint for partitioning key writeDao.postCreateGraph(savedMetadata); }
private void splitMultiPolygons(){ List<Geometry>clone=new ArrayList<>(maskGeometries); for(Geometry gt:clone){ if(gt instanceof MultiPolygon){ int n=gt.getNumGeometries(); for(int i=0;i<n;i++){ Polygon pp=(Polygon)gt.getGeometryN(i); maskGeometries.add(pp); } maskGeometries.remove(gt); } } }
/** * 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; }
/** * Box with extent of the upper right tile at zoom level 4. * * @return geometry */ public static Polygon createUpperRightExtremeZ4() { return createPolygonXy("ISO BOX", "Upper Right Box", new double[][]{ {180, 85.05112877980659}, {157.5, 85.05112877980659}, {157.5, 82.67628497834903}, {180, 82.67628497834903}, {180, 85.05112877980659} }); }
/** * Polygon of Bermuda. * * @return geometry */ public static Polygon bermuda() { return createPolygonXy("ISO BM", "Bermuda", new double[][]{ {-64.68681335449219, 32.407211836256685}, {-64.93263244628906, 32.28423019803735}, {-64.87907409667969, 32.204086355917944}, {-64.6270751953125, 32.34980253736092}, {-64.68681335449219, 32.407211836256685} }); }
public boolean execute() { done = false; new Thread(new Runnable() { public void run() { notifyEvent(new SumoActionEvent(SumoActionEvent.STARTACTION,"Importing land coastline "+name,-1)); try { ImageLayer l=LayerManager.getIstanceManager().getCurrentImageLayer(); if(l!=null){ try { Polygon imageP=((SarImageReader)l.getImageReader()).getBbox(PlatformConfiguration.getConfigurationInstance().getLandMaskMargin(0)); GeometryImage gl = SimpleShapefile.createIntersectedLayer(worldFile, imageP,l.getImageReader().getGeoTransform()); int t=MaskVectorLayer.COASTLINE_MASK; //if(args[1].equalsIgnoreCase("ice")) // t=MaskVectorLayer.ICE_MASK; GenericLayer mask=FactoryLayer.createMaskLayer(gl,t); LayerManager.addLayerInThread(mask); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } } catch (Exception e) { } notifyEvent(new SumoActionEvent(SumoActionEvent.ENDACTION,"",-1)); } }).start(); return true; }
public int compare (Polygon p1, Polygon p2) { double a1 = p1.getArea(); double a2 = p2.getArea(); if (a1 < a2) { return(1); } else if (a1 > a2) { return(-1); } else { return(0); } }
public int compare (Polygon p1, Polygon p2) { if (p1.contains(p2)) { return(1); } else if (p2.contains(p1)) { return(-1); } else { return(0); } }
/** * * @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); }
static Polygon createPolygonXy(String id, String name, double[][] coordinates) { Coordinate[] temp = new Coordinate[coordinates.length]; for (int i = 0; i < coordinates.length; i++) { temp[i] = new Coordinate(coordinates[i][0], coordinates[i][1]); } Polygon polygon = GEOMETRY_FACTORY.createPolygon(temp); Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("id", id.hashCode()); attributes.put("name", name); polygon.setUserData(attributes); return polygon; }
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; }
public void addCoordinateArrays(final Geometry geometry, final boolean orientPolygons, final List<Coordinate[]> coordArrayList) { if (geometry.getDimension() <= 0) { return; } else if (geometry instanceof LineString) { final LineString l = (LineString) geometry; coordArrayList.add(l.getCoordinates()); } else if (geometry instanceof Polygon) { final Polygon poly = (Polygon) geometry; Coordinate[] shell = poly.getExteriorRing().getCoordinates(); if (orientPolygons) { shell = ensureOrientation(CGAlgorithms.CLOCKWISE, shell); } coordArrayList.add(shell); for (int numRing = 0; numRing < poly.getNumInteriorRing(); numRing++) { Coordinate[] hole = poly.getInteriorRingN(numRing).getCoordinates(); if (orientPolygons) { hole = ensureOrientation( CGAlgorithms.COUNTERCLOCKWISE, hole); } coordArrayList.add(hole); } } else if (geometry instanceof GeometryCollection) { final GeometryCollection gc = (GeometryCollection) geometry; for (int numGeom = 0; numGeom < gc.getNumGeometries(); numGeom++) { addCoordinateArrays(gc.getGeometryN(numGeom), orientPolygons, coordArrayList); } } }
private static Geometry smooth(final Geometry geom, final double fit, final GeometryFactory factory, GeometrySmoother smoother) { switch (geom.getGeometryType().toUpperCase()) { case "POINT": case "MULTIPOINT": // For points, just return the input geometry return geom; case "LINESTRING": // This handles open and closed lines (LinearRings) return smoothLineString(factory, smoother, geom, fit); case "MULTILINESTRING": return smoothMultiLineString(factory, smoother, geom, fit); case "POLYGON": return smoother.smooth((Polygon) geom, fit); case "MULTIPOLYGON": return smoothMultiPolygon(factory, smoother, geom, fit); case "GEOMETRYCOLLECTION": return smoothGeometryCollection(factory, smoother, geom, fit); default: throw new UnsupportedOperationException("No smoothing method available for " + geom.getGeometryType()); } }
public BufferedImage rasterize(BufferedImage image, int offsetX, int offsetY, double scalingFactor) { Rectangle rect = image.getRaster().getBounds(); GeometryFactory gf = new GeometryFactory(); Coordinate[] coords = new Coordinate[]{ new Coordinate((int) (((double) rect.getMinX() / scalingFactor) + offsetX), (int) (((double) rect.getMinY() / scalingFactor) + offsetY)), new Coordinate((int) (((double) rect.getMaxX() / scalingFactor) + offsetX), (int) (((double) rect.getMinY() / scalingFactor) + offsetY)), new Coordinate((int) (((double) rect.getMaxX() / scalingFactor) + offsetX), (int) (((double) rect.getMaxY() / scalingFactor) + offsetY)), new Coordinate((int) (((double) rect.getMinX() / scalingFactor) + offsetX), (int) (((double) rect.getMaxY() / scalingFactor) + offsetY)), new Coordinate((int) (((double) rect.getMinX() / scalingFactor) + offsetX), (int) (((double) rect.getMinY() / scalingFactor) + offsetY)), }; Polygon geom = gf.createPolygon(gf.createLinearRing(coords), null); Graphics g2d = image.getGraphics(); g2d.setColor(Color.WHITE); 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 - offsetX) * scalingFactor); yPoints[i++] = (int) ((c.y - offsetY) * scalingFactor); } g2d.fillPolygon(xPoints, yPoints, p.getNumPoints()); } } g2d.dispose(); return image; }
/** * * @param reader * @return */ protected GeometryImage readShapeFile(String shpFilePath,Polygon imgBox,GeoTransform gt){ GeometryImage gl=null; try { gl = SimpleShapefile.createIntersectedLayer(new File(shpFilePath),imgBox,gt); } catch (Exception e) { logger.error(e.getMessage(),e); } return gl; }
public static Polygon toGeometry(final Envelope env, GeometryFactory factory) { ensureNonNull("env", env); Polygon polygon = factory.createPolygon( factory.createLinearRing(new Coordinate[] { new Coordinate(env.getMinX(), env.getMinY()), new Coordinate(env.getMaxX(), env.getMinY()), new Coordinate(env.getMaxX(), env.getMaxY()), new Coordinate(env.getMinX(), env.getMaxY()), new Coordinate(env.getMinX(), env.getMinY()) }), null); return polygon; }
@Test public void should_not_split_small_polygon() { Polygon polygon = polygon( new Coordinate(0.0, 0.0), new Coordinate(1.0, 0.0), new Coordinate(1.0, 1.0), new Coordinate(0.0, 1.0), new Coordinate(0.0, 0.0)); List<Geometry> geoms = LargePolygonSplitter.split(polygon, 10); assertThat(geoms).containsExactly(polygon); }
/** * * @param margin * @return * @throws Exception */ public Polygon getBbox(int margin) throws Exception{ if(bbox==null) try { bbox=buildBox(margin); } catch (CQLException | ParseException | GeoTransformException e) { logger.error(e.getMessage(),e); throw e; } return bbox; }
/** * Box with extent of the lower left tile at zoom level 4. * * @return geometry */ public static Polygon createLowerLeftExtremeZ4() { return createPolygonXy("ISO BOX", "Upper Left Box", new double[][]{ {-180, -85.05112877980659}, {-157.5, -85.05112877980659}, {-157.5, -82.67628497834903}, {-180, -82.67628497834903}, {-180, -85.05112877980659} }); }
public void testNewPolygon() { Polygon polygon = ShapeBuilders.newPolygon(new CoordinatesBuilder() .coordinate(-45, 30) .coordinate(45, 30) .coordinate(45, -30) .coordinate(-45, -30) .coordinate(-45, 30)).toPolygon(); LineString exterior = polygon.getExteriorRing(); assertEquals(exterior.getCoordinateN(0), new Coordinate(-45, 30)); assertEquals(exterior.getCoordinateN(1), new Coordinate(45, 30)); assertEquals(exterior.getCoordinateN(2), new Coordinate(45, -30)); assertEquals(exterior.getCoordinateN(3), new Coordinate(-45, -30)); }
public static double getArea(Geometry geom, Boolean inMeters) throws Exception { if (inMeters) { if (geom instanceof Polygon) { Polygon poly = (Polygon) geom; double area = Math.abs(getSignedArea(poly.getExteriorRing().getCoordinateSequence())); for (int i = 0; i < poly.getNumInteriorRing(); i++) { LineString hole = poly.getInteriorRingN(i); area -= Math.abs(getSignedArea(hole.getCoordinateSequence())); } return area; } else if (geom instanceof LineString) { LineString ring = (LineString)geom; return getSignedArea(ring.getCoordinateSequence()); } else { if (TRANSFORM_WGS84_SPHERICALMERCATOR == null) { String wkt = "PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],AUTHORITY[\"EPSG\",\"3857\"]]"; CoordinateReferenceSystem crs = CRS.parseWKT(wkt);// CRS.decode("EPSG:3857"); TRANSFORM_WGS84_SPHERICALMERCATOR = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crs, true); } Geometry transformedGeometry = JTS.transform(geom, TRANSFORM_WGS84_SPHERICALMERCATOR); return transformedGeometry.getArea(); } } else { return geom.getArea(); } }
public static void assertEquals(Polygon p1, Polygon p2) { Assert.assertEquals(p1.getNumInteriorRing(), p2.getNumInteriorRing()); assertEquals(p1.getExteriorRing(), p2.getExteriorRing()); // TODO: This test do not check all permutations of linestrings. So the test // fails if the holes of the polygons are not ordered the same way for (int i = 0; i < p1.getNumInteriorRing(); i++) { assertEquals(p1.getInteriorRingN(i), p2.getInteriorRingN(i)); } }
@Override public IWayGraphVersionMetadata mapRow(ResultSet rs, int rowNum) throws SQLException { IWayGraphVersionMetadata md = new WayGraphVersionMetadata(rs.getLong("id"), rs.getLong("graph_id"), rs.getString("graphname"), rs.getString("version"), rs.getString("origin_graphname"), rs.getString("origin_version"), State.valueOf(rs.getString("state")), rs.getTimestamp("valid_from"), rs.getTimestamp("valid_to"), (Polygon) bp.parse(rs.getBytes("covered_area")), rs.getInt("segments_count"), rs.getInt("connections_count"), RowMapperUtils.convertAccessTypes(rs, "accesstypes"), (Map<String, String>) rs.getObject("tags"), new Source(rs.getInt("source_id"), rs.getString("source_name")), rs.getString("type"), rs.getString("description"), rs.getTimestamp("creation_timestamp"), rs.getTimestamp("storage_timestamp"), rs.getString("creator"), rs.getString("origin_url")); return md; }
@Override public IWayGraphView mapRow(ResultSet rs, int rowNum) throws SQLException { byte[] coveredAreaBytes = rs.getBytes("covered_area"); return new WayGraphView(rs.getString("viewname"), new WayGraph(rs.getLong("graph_id"), rs.getString("graph_name")), rs.getString("dbviewname"), rs.getBoolean("waysegments_included"), (coveredAreaBytes == null ? null : (Polygon) bp.parse(coveredAreaBytes)), rs.getInt("segments_count"), rs.getInt("connections_count"), (Map<String, String>) rs.getObject("tags")); }