/** */ 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 JTS Footprint validity */ public static boolean checkJTSFootprint (String footprint) { try { WKTReader wkt = new WKTReader(); Geometry geom = wkt.read(footprint); IsValidOp vaildOp = new IsValidOp(geom); TopologyValidationError err = vaildOp.getValidationError(); if (err != null) { throw new IllegalParameterException(err.getMessage()); } return true; } catch (Exception e) { LOGGER.error("JTS Footprint error : " + e.getMessage()); return false; } }
public BlackBorderAnalysis(GeoImageReader gir,int hTileSize,int vTileSize,List<Geometry> land) { this.gir=gir; //if there is an image with cross-pol (HV or VH) we use it int nb=gir.getNBand(); if(nb>1){ for(int i=0;i<nb;i++){ if(gir.getBandName(i).equalsIgnoreCase("HV")||gir.getBandName(i).equalsIgnoreCase("VH")){ bandAnalysis=i; break; } } } // the real size of tiles sizeX = hTileSize; //x step sizeY = vTileSize; //y step horTiles=gir.getWidth()/hTileSize; verTiles=gir.getHeight()/vTileSize; iNPixExtremes=hTileSize<vTileSize?vTileSize/10:hTileSize/10; this.land=land; }
/** * 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; }
private static FeatureStats polyStats(Geometry geom) { final FeatureStats featureStats = new FeatureStats(); for (int i = 0; i < geom.getNumGeometries(); ++i) { final Polygon nextPoly = (Polygon) geom.getGeometryN(i); // Stats: exterior ring final LineString exteriorRing = nextPoly.getExteriorRing(); featureStats.totalPts += exteriorRing.getNumPoints(); featureStats.repeatedPts += checkRepeatedPoints2d(exteriorRing); // Stats: interior rings for (int ringIndex = 0; ringIndex < nextPoly.getNumInteriorRing(); ++ringIndex) { final LineString nextInteriorRing = nextPoly.getInteriorRingN(ringIndex); featureStats.totalPts += nextInteriorRing.getNumPoints(); featureStats.repeatedPts += checkRepeatedPoints2d(nextInteriorRing); } } return featureStats; }
/** * Print geometries. * * @param geoms the geometries * @throws IOException thrown when IO error */ public static void printGeoms(Collection<Geometry> geoms) throws IOException { System.out.println("Attribute Info"); System.out.println("---------------"); for (Geometry geom : geoms) { if (geom.getUserData() == null) { System.out.println("no user data"); return; } Map<?,?> attributes = (Map) geom.getUserData(); for (Map.Entry entry : attributes.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } System.out.println(""); } }
@Override public List<String> getEnvelope(final List<String> wkts) throws IllegalArgumentException { Geometry resultGeometry = null; final List<String> result = new ArrayList<String>(); for (final String wkt : wkts) { Geometry geom = getGeometry(wkt); geom = geom.buffer(TOLERANCIA_ENVELOPE); if (resultGeometry == null) { resultGeometry = geom; } else { resultGeometry = resultGeometry.union(geom); } } if (resultGeometry != null) { result.add(resultGeometry.getEnvelope().toText()); } return result; }
public static Geometry getFrame(GeoImageReader gir) throws GeoTransformException{ try { GeoTransform gt = gir.getGeoTransform(); double[] x0; double[] x1; double[] x2; double[] x3; x0 = gt.getGeoFromPixel(-50, -50); x2 = gt.getGeoFromPixel(50 + gir.getWidth(), 50 + gir.getHeight()); x3 = gt.getGeoFromPixel(50 + gir.getWidth(), -50); x1 = gt.getGeoFromPixel(-50, 50 + gir.getHeight()); return new WKTReader().read("POLYGON((" + x0[0] + " " + x0[1] + "," + x1[0] + " " + x1[1] + "," + x2[0] + " " + x2[1] + "," + x3[0] + " " + x3[1] + "," + x0[0] + " " + x0[1] + "" + "))"); } catch (ParseException ex) { logger.error(ex.getMessage(),ex); } return null; }
/** */ public static double getSharedAreaRatio (Geometry geom1, Geometry geom2) { try { return geom1.intersection(geom2).getArea() / geom1.getArea(); } catch (TopologyException e) { // HACK: there appears to be a bug in JTS, but I can't // reproduce it consistently. Why should computing the // intersection with a MultiPolygon fail when computing // the intersection with each of its constituent Polygons // succeeds? I have no idea, but it does happen. This // seems to fix the problem, though. double result = 0.0; if (geom2 instanceof GeometryCollection) { GeometryCollection gc = (GeometryCollection)geom2; for (int j = 0; j < gc.getNumGeometries(); j += 1) { result += geom1.intersection(gc.getGeometryN(j)).getArea(); } return result / geom1.getArea(); } else { throw e; } } }
@Test public void testNegExtPolyRings() { try { // Single MultiPolygon with two triangles that have negative area from shoelace formula // Support for 'V1' MVTs. final JtsMvt mvt = loadMvt( "src/test/resources/mapbox/vector_tile_js/multi_poly_neg_exters.mvt", MvtReader.RING_CLASSIFIER_V1); final List<Geometry> geoms = getAllGeometries(mvt); assertEquals(1, geoms.size()); assertTrue(geoms.get(0) instanceof MultiPolygon); } catch (IOException exception) { fail(exception.getMessage()); } }
/** * * @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; } } } } }
private static List<IsochronesIntersection> computeIntersection(IsochronesIntersection isoIntersection, Integer intersectionIndex, List<IsochronesIntersection> intersections) { List<IsochronesIntersection> result = null; for (int i = intersectionIndex + 1 ; i < intersections.size(); i++) { IsochronesIntersection isoIntersection2 = intersections.get(i); if (isoIntersection.intersects(isoIntersection2)) { Geometry geomIntersection = isoIntersection.getGeometry().intersection(isoIntersection2.getGeometry()); if (geomIntersection != null) { if (result == null) result = new ArrayList<IsochronesIntersection>(); IsochronesIntersection isoIntersectionNew = new IsochronesIntersection(geomIntersection); isoIntersectionNew.addContourRefs(isoIntersection.getContourRefs()); isoIntersectionNew.addContourRefs(isoIntersection2.getContourRefs()); } } } return result; }
/** * * @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; }
/** * * @param bufferedGeom * @param bufferDistance * @return * @throws InterruptedException * @throws ExecutionException */ private List<Geometry> parallelBuffer(List<Geometry> bufferedGeom,double bufferDistance)throws InterruptedException, ExecutionException { int processors = Runtime.getRuntime().availableProcessors(); ThreadPoolExecutor executor = new ThreadPoolExecutor(2, processors, 5000, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); List<Callable<Geometry>> tasks = new ArrayList<Callable<Geometry>>(); for (int i=0;i<bufferedGeom.size();i++) { tasks.add(new ParallelBuffer(bufferedGeom.get(i),bufferDistance)); } List<Future<Geometry>> results = executor.invokeAll(tasks); executor.shutdown(); List<Geometry> geoms = new ArrayList<Geometry>(); for (Future<Geometry> result : results) { List<Geometry> l = Arrays.asList(result.get()); geoms.addAll(l); } return geoms; }
private void doSelect() { if (whereClause != null) { try { Connection conn = DriverManager.getConnection("jdbc:h2:~/.sumo/VectorData;AUTO_SERVER=TRUE", "sa", ""); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT * FROM \"" + glayer.getName() + "\" WHERE " + whereClause); WKTReader wkt = new WKTReader(); String[] schema = glayer.getSchema(); //TODO:schema type problem check!! //String[] types = glayer.getSchemaTypes(); glayer.clear(); while (rs.next()) { Geometry geom = wkt.read(rs.getString("geom")); AttributesGeometry att = new AttributesGeometry(schema); for (String key : schema) { att.set(key, rs.getString(key)); } glayer.put(geom, att); } } catch (Exception ex) { logger.error(ex.getMessage(),ex); } whereClause = null; } }
private void createRenderedGeometries() { Vector<Geometry> templ=new Vector<Geometry>(); for (Geometry temp : glayer.getGeometries()) { Date date=datesOfgeoms.get(temp); if (minimumDate.before(date) && maximumDate.after(date)) { templ.add(temp); } } while(onWork){ try { Thread.sleep(25); } catch (InterruptedException ex) { logger.error(ex.getMessage(),ex); } } onWork=true; renderedLayer.clear(); renderedLayer=templ; onWork=false; }
private static void fragment(Geometry geometry, String layerName, int min, int max, Map<Key, JtsMvt> bucket) { for (int z = min; z <= max; z++) { int[] tilingSchemeBoundingBox = getTilingSchemeBoundingBox(z, geometry); int minx = tilingSchemeBoundingBox[0]; int miny = tilingSchemeBoundingBox[1]; int maxx = tilingSchemeBoundingBox[2]; int maxy = tilingSchemeBoundingBox[3]; // these are the cells of interest (ones that the geometry may cover) for (int x = minx; x <= maxx; x++) { for (int y = miny; y <= maxy; y++) { addToStaging(z, x, y, layerName, geometry, bucket); } } } }
protected List<Geometry> getList(final List<String> wktLayer) { final List<Geometry> result = new ArrayList<Geometry>(); for (final String wkt : wktLayer) { result.add(getGeometry(wkt)); } return result; }
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; }
private static Geometry smoothMultiLineString(GeometryFactory factory, GeometrySmoother smoother, Geometry geom, double fit) { final int N = geom.getNumGeometries(); LineString[] smoothed = new LineString[N]; for (int i = 0; i < N; i++) { smoothed[i] = (LineString) smoothLineString(factory, smoother, geom.getGeometryN(i), fit); } return factory.createMultiLineString(smoothed); }
/** * * @param ft * @param glayer * @param projection * @param gt * @return * @throws Exception */ public static FeatureCollection<SimpleFeatureType,SimpleFeature> createFeatures(SimpleFeatureType ft, GeometryImage glayer, String projection) throws Exception { DefaultFeatureCollection collection = new DefaultFeatureCollection(); int id=0; for (Geometry geom : glayer.getGeometries()) { Object[] data = new Object[ft.getDescriptors().size()]; System.arraycopy(glayer.getAttributes(geom).getValues(), 0, data, 1, data.length-1); data[0] = geom; SimpleFeature simplefeature = SimpleFeatureBuilder.build(ft, data, ""+id); collection.add(simplefeature); /*if (geom instanceof Point) { Object[] data = new Object[ft.getDescriptors().size()]; System.arraycopy(glayer.getAttributes(geom).getValues(), 0, data, 1, data.length-1); data[0] = geom; SimpleFeature simplefeature = SimpleFeatureBuilder.build(ft, data, ""+id); collection.add(simplefeature); } else if (geom instanceof Polygon) { Object[] data = new Object[glayer.getSchema().length]; System.arraycopy(glayer.getAttributes(geom).getValues(), 0, data, 0, data.length ); SimpleFeature simplefeature = SimpleFeatureBuilder.build(ft, data, ""+id); collection.add(simplefeature); data = null; } else if (geom instanceof LineString) { Object[] data = new Object[glayer.getSchema().length + 1]; data[0] = geom; System.arraycopy(glayer.getAttributes(geom).getValues(), 0, data, 1, data.length - 1); SimpleFeature simplefeature = SimpleFeatureBuilder.build(ft, data, ""+id); collection.add(simplefeature); }*/ id++; } return collection; }
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; }
private PoseSteering[] computePath(PoseSteering from, PoseSteering ... to) { if (USE_MP) { ReedsSheppCarPlanner rsp = new ReedsSheppCarPlanner(); if (this.mapFileName == null) { rsp.setMapFilename(makeEmptyMapMap()); rsp.setMapResolution(1.0); } else { rsp.setMapFilename(mapImgFileName); rsp.setMapResolution(mapRes); } rsp.setRadius(3.0); rsp.setTurningRadius(MAX_TURNING_RADIUS); rsp.setDistanceBetweenPathPoints(MIN_DISTANCE_BETWEEN_PATH_POINTS); rsp.setStart(from.getPose()); Pose[] goalPoses = new Pose[to.length]; for (int i = 0; i < goalPoses.length; i++) goalPoses[i] = to[i].getPose(); rsp.setGoals(goalPoses); rsp.addObstacles(obstacles.toArray(new Geometry[obstacles.size()])); if (!rsp.plan()) return null; PoseSteering[] ret = rsp.getPath(); return ret; } Coordinate[] controlPoints = new Coordinate[4]; controlPoints[0] = new Coordinate(from.getX(),from.getY(),0.0); double d = MAX_TURNING_RADIUS; controlPoints[1] = new Coordinate(from.getX()+d*Math.cos(from.getTheta()), from.getY()+d*Math.sin(from.getTheta()), 0.0); controlPoints[2] = new Coordinate(to[to.length-1].getX()-d*Math.cos(to[to.length-1].getTheta()), to[to.length-1].getY()-d*Math.sin(to[to.length-1].getTheta()), 0.0); controlPoints[3] = new Coordinate(to[to.length-1].getX(),to[to.length-1].getY(),0.0); Spline3D spline1 = SplineFactory.createBezier(controlPoints, 0.5); return spline1.asPoseSteerings(); }
/** * Validate the JtsLayer. * * @param name mvt layer name * @param geometries geometries in the tile * @throws IllegalArgumentException when {@code name} or {@code geometries} are null */ private static void validate(String name, Collection<Geometry> geometries) { if (name == null) { throw new IllegalArgumentException("layer name is null"); } if (geometries == null) { throw new IllegalArgumentException("geometry collection is null"); } }
@Override public List<Geometry> parse(Entry entry) throws IOException { // TODO REMOVE THIS OBSOLETE CLASS - it flattens layers final byte[] bytes = entry.getVector(); final InputStream is = new ByteArrayInputStream(bytes); List<Geometry> allgeoms = new ArrayList<>(); JtsMvt result = MvtReader.loadMvt(is, GEOMETRY_FACORY, new TagKeyValueMapConverter()); for (JtsLayer l : result.getLayers()) { allgeoms.addAll(l.getGeometries()); } return allgeoms; }
@Test public void simpleTest() { try { // Load multipolygon z0 tile final JtsMvt mvt = loadMvt("src/test/resources/vec_tile_test/0/0/0.mvt"); List<Geometry> geoms = getAllGeometries(mvt); // Debug stats of multipolygon final JtsGeomStats stats = JtsGeomStats.getStats(geoms); LoggerFactory.getLogger(MvtReaderTest.class).info("Stats: {}", stats); } catch (IOException exception) { fail(exception.getMessage()); } }
public static double getLength(Geometry geom, Boolean inMeters) throws Exception { if (!(geom instanceof LineString)) throw new Exception("Specified geometry type is not supported."); LineString ls = (LineString)geom; if (ls.getNumPoints() == 0) return 0.0; if (inMeters) { double length = 0.0; DistanceCalc dc = new DistanceCalcEarth(); Coordinate c0 = ls.getCoordinateN(0); for (int i = 1; i < ls.getNumPoints(); ++i) { Coordinate c1 = ls.getCoordinateN(i); length += dc.calcDist(c0.y, c0.x, c1.y, c1.x); c0 = c1; } return length; } else return ls.getLength(); }
public Object getValueAt(int rowIndex, int columnIndex) { Geometry geom = gl.getGeometries().get(rowIndex); if (columnIndex == 0) { return geom; } else { return gl.getAttributes(geom).get(gl.getSchema()[columnIndex - 1]); } }
@SuppressWarnings("unchecked") private static List<Geometry> splittedWorld(STRtree tree) { return LargePolygonSplitter.split(world(), 5, g -> { List<Geometry> query = tree.query(g.getEnvelopeInternal()); return query.stream().mapToInt(Geometry::getNumPoints).sum() < 2000; }); }
public List<String> divide(final String wktCorte, final String wktIntersected) throws IllegalArgumentException { final List<String> wkts = new ArrayList<String>(); try { final Geometry geomCorte = getGeometry(wktCorte); final Geometry geomIntersected = getGeometry(wktIntersected); if (geomIntersected == null || geomCorte == null) { throw new RuntimeException("Existen geometría nulas"); } final Collection<Geometry> lines = getLines((Polygon) geomIntersected, (LineString) geomCorte); final Collection<Geometry> nodedLines = lineNoder.nodeLines(lines); final Collection<Geometry> polygons = lineNoder.polygonizer(nodedLines); for (final Geometry pol : polygons) { wkts.add(pol.toText()); } } catch (Exception e) { throw new IllegalArgumentException("Error no controlado: " + e.getMessage(), e); } return wkts; }
/** * Update the geo filter configuration from user supplied GeoFilter property. * * @param geo_filter the content of the GeoFilter property * @throws InvalidValueException if GeoFilter is invalid */ private void updateGeoFilter(String geo_filter) throws InvalidValueException { if (geo_filter == null || geo_filter.isEmpty()) { this.syncConf.removeConfig("geofilter_op"); this.syncConf.removeConfig("geofilter_shape"); } else { Pattern pattern = Pattern.compile("(disjoint|within|contains|intersects) (.+)"); Matcher matcher = pattern.matcher(geo_filter); if (!matcher.matches()) { throw new InvalidValueException(SynchronizerEntitySet.GEO_FILTER, geo_filter); } String operator = matcher.group(1); String wkt = matcher.group(2); WKTReader wkt_reader = new WKTReader(); try { Geometry geometry = wkt_reader.read(wkt); if (!geometry.isValid()) { throw new InvalidValueException(SynchronizerEntitySet.GEO_FILTER, geo_filter); } this.syncConf.setConfig("geofilter_op", operator); this.syncConf.setConfig("geofilter_shape", wkt); } catch (com.vividsolutions.jts.io.ParseException ex) { throw new InvalidValueException(SynchronizerEntitySet.GEO_FILTER, geo_filter); } } }
private boolean validateMinSegmentLength(final Geometry geom) { final List<Coordinate[]> arrays = topologyUtil.toCoordinateArrays(geom, false); boolean isValid = true; for (final Coordinate[] coordinates: arrays) { if (!validateMinSegmentLength(geom, coordinates)) { isValid = false; break; } } return isValid; }
/** * Modify the GeometricLayer so the layer coordinates system matches the world coordinate system (EPSG projection). * @throws GeoTransformException */ public static GeometryImage createWorldProjectedLayer(GeometryImage oldPositions, GeoTransform geoTransform, String projection) throws GeoTransformException { GeometryImage positions=oldPositions.clone(); //Coordinate previous=new Coordinate(0,0); for(Geometry geom:positions.geoms){ geom=geoTransform.transformGeometryGeoFromPixel(geom); /*for(Coordinate pos:geom.getCoordinates()){ double[] temp=geoTransform.getGeoFromPixel(pos.x, pos.y); pos.x=temp[0]; pos.y=temp[1]; }*/ } return positions; }
/** * */ public void splitMultiPolygons(){ List<Geometry>clone=new ArrayList<>(this.geoms); 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); put(pp,(AttributesGeometry)pp.getUserData()); } geoms.remove(gt); } } }
@Override public LineString deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Geometry geom = parse(jp); if(geom instanceof LineString) { return (LineString)geom; } throw new JsonParseException(jp, "parsed geometry was not a LineString!", jp.getCurrentLocation()); }
/** * tests a coordinate transformation from epsg:4236 --> epsg:4817 */ @Test public void testCorrect4817Transform() { algo.setTargetEPSG("EPSG:4817"); try { algo.runAlgorithm(); FeatureCollection fc = algo.getResult(); FeatureIterator<?> featureIterator = fc.features(); SimpleFeature feature = (SimpleFeature) featureIterator.next(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); Coordinate[] coords = geometry.getCoordinates(); assertEquals(41.2178843506, coords[0].x, 0.001); assertEquals(8.95903973526, coords[0].y, 0.001); assertEquals(37.4710724824, coords[1].x, 0.001); assertEquals(8.13026146044, coords[1].y, 0.001); assertEquals(41.473842952, coords[2].x, 0.001); assertEquals(7.90771407361, coords[2].y, 0.001); assertEquals(41.1162889713, coords[3].x, 0.001); assertEquals(7.70767521468, coords[3].y, 0.001); assertEquals(39.4162959551, coords[4].x, 0.001); assertEquals(6.91879868251, coords[4].y, 0.001); FeatureCollection result = algo.getResult(); } catch (Exception e) { fail("Exception thrown: " + e.getMessage()); } }
@Test public void testLayerCollection() { String layerName = "Points of Interest"; List<Geometry> geometries = new ArrayList<>(); JtsLayer layer = new JtsLayer(layerName, geometries); String actualName = layer.getName(); String expectedName = layerName; assertEquals(expectedName, actualName); Collection<Geometry> actualGeometry = layer.getGeometries(); Collection<Geometry> expectedGeometry = geometries; assertEquals(expectedGeometry, actualGeometry); }
private List<Geometry> getSegments(Geometry sourceLines, List<Geometry> lines) { List<Geometry> segments = new ArrayList<Geometry>(); for (Geometry line : lines) { if (sourceLines.intersects(line) && !line.crosses(sourceLines)) { segments.add(line); } } return segments; }