public static List<LineString> split(LineString given, int maxPoint) { List<LineString> result = newArrayList(); Coordinate[] coordinates = given.getCoordinates(); int current = 0; while (current < coordinates.length) { int end = current + maxPoint - 1; if (coordinates.length - end < 2) { result.add(gf.createLineString(Arrays.copyOfRange(coordinates, current, coordinates.length))); return result; } else { result.add(gf.createLineString(Arrays.copyOfRange(coordinates, current, end + 1))); current = end; } } throw new IllegalStateException("Unexpected"); }
@Test public void should_return_same_geom_if_necessary() { LineString linestring = linestring( new Coordinate(0.0, 0.0), new Coordinate(1.0, 0.0), new Coordinate(1.0, 1.0)); List<LineString> lines = LongLineSplitter.split(linestring, 3); assertThat(lines).containsExactly( linestring( new Coordinate(0.0, 0.0), new Coordinate(1.0, 0.0), new Coordinate(1.0, 1.0))); assertThat(lines).isEqualTo(LongLineSplitter.split(linestring, 4)); assertThat(lines).isEqualTo(LongLineSplitter.split(linestring, 5)); }
private static final double[] range(Coordinate[] points, int offset, int length) { double minX = points[0].x; double maxX = points[0].x; double minY = points[0].y; double maxY = points[0].y; // compute the bounding coordinates (@todo: cleanup brute force) for (int i = 1; i < length; ++i) { if (points[offset + i].x < minX) { minX = points[offset + i].x; } if (points[offset + i].x > maxX) { maxX = points[offset + i].x; } if (points[offset + i].y < minY) { minY = points[offset + i].y; } if (points[offset + i].y > maxY) { maxY = points[offset + i].y; } } return new double[] {minX, maxX, minY, maxY}; }
/** * Create a Catmull-Rom spline based on the given control points. * The generated curve starts in the first control point and ends * in the last control point. * In addition, the curve intersects all the control points. * * @param controlPoints Control points of spline. * @param maxDist Maximum distance between points along the spline. * @return A Catmull-Rom spline based on the given control points. */ public static Spline3D createCatmullRom (Coordinate[] controlPoints, double maxDist) { double[] cPoints = new double[controlPoints.length*3]; int counter = 0; for (int i = 0; i < controlPoints.length; i++) { cPoints[counter] = controlPoints[i].x; cPoints[counter+1] = controlPoints[i].y; cPoints[counter+2] = controlPoints[i].z; counter+=3; } int numParts = 3; Spline3D ret = null; do { ret = new Spline3D(new CatmullRomSpline (cPoints, numParts++).generate(), controlPoints, Spline3D.Type.SPLINE_CATMULL_ROM); } while(ret.computeMinMaxDistances()[1] > maxDist); return ret; }
private void addBufferPoints(List<Coordinate> points, Quadtree tree, double lon0, double lat0, double lon1, double lat1, boolean addLast, boolean checkNeighbours, double bufferSize) { double dx = (lon0 - lon1); double dy = (lat0 - lat1); double norm_length = Math.sqrt((dx * dx) + (dy * dy)); double scale = bufferSize /norm_length; double dx2 = -dy*scale; double dy2 = dx*scale; addPoint(points, tree, lon0 + dx2, lat0 + dy2, checkNeighbours); addPoint(points, tree, lon0 - dx2, lat0 - dy2, checkNeighbours); // add a middle point if two points are too far from each other if (norm_length > 2*bufferSize) { addPoint(points, tree, (lon0 + lon1)/2.0 + dx2, (lat0 + lat1)/2.0 + dy2, checkNeighbours); addPoint(points, tree, (lon0 + lon1)/2.0 - dx2, (lat0 + lat1)/2.0 - dy2, checkNeighbours); } if (addLast) { addPoint(points, tree, lon1 + dx2, lat1 + dy2, checkNeighbours); addPoint(points, tree, lon1 - dx2, lat1 - dy2, checkNeighbours); } }
/** * * @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; } } } } }
/** * * @param gl * @param cs * @param width * @param height * @param x * @param y */ protected void drawPoly(GL2 gl,Coordinate[] cs,float width,float height,int x,int y,float rwidth){ gl.glLineWidth(rwidth); gl.glBegin(GL.GL_LINE_STRIP); for (int p = 0; p < cs.length; p++) { double vx=(cs[p].x - x) / width; double vy=1 - (cs[p].y - y) / height; gl.glVertex2d(vx,vy); } //close polygon Coordinate point = cs[0]; gl.glVertex2d((point.x - x) / width, 1 - (point.y - y) / height); gl.glEnd(); gl.glFlush(); }
@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))"); }
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; }
/** * Method that calculate the total length between the points of a coordinate * array * * @param cArray * Array of Coordinate * @return dLength double Value Length */ public static double calculateLengthWGS84(Coordinate[] cArray) { double length = 0; int nLength = cArray.length; if (nLength > 0) { Coordinate c0 = cArray[0]; Coordinate c1 = null; for (int index = 1; index < nLength; index++) { c1 = cArray[index]; length += calcDistHaversine(c0.x, c0.y, c1.x, c1.y); c0 = c1; } } return length; }
public static Coordinate[] parse(String value, String separator, boolean is3D, boolean inverseXY) { String[] coordValues = value.split(separator); Coordinate[] coords = new Coordinate[coordValues.length]; for (int i = 0; i < coordValues.length; i++) { String[] locations = coordValues[i].split(","); if (inverseXY) { if (is3D && locations.length == 3) coords[i] = new Coordinate(Double.parseDouble(locations[1]), Double.parseDouble(locations[0]), Double.parseDouble(locations[2])); else coords[i] = new Coordinate(Double.parseDouble(locations[1]), Double.parseDouble(locations[0])); } else { if (is3D && locations.length == 3) coords[i] = new Coordinate(Double.parseDouble(locations[0]), Double.parseDouble(locations[1]), Double.parseDouble(locations[2])); else coords[i] = new Coordinate(Double.parseDouble(locations[0]), Double.parseDouble(locations[1])); } } return coords; }
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"); } }
public MatrixSearchContext create(Graph graph, Coordinate[] sources, Coordinate[] destinations, double maxSearchRadius) throws Exception { if (_locationCache == null) _locationCache = new HashMap<Coordinate, LocationEntry>(); else _locationCache.clear(); QueryGraph queryGraph = new QueryGraph(graph); List<QueryResult> queryResults = new ArrayList<QueryResult>(sources.length + destinations.length); resolveLocations(sources, queryResults, maxSearchRadius); resolveLocations(destinations, queryResults, maxSearchRadius); queryGraph.lookup(queryResults, _buffer); MatrixLocations mlSources = createLocations(sources); MatrixLocations mlDestinations = createLocations(destinations); return new MatrixSearchContext(queryGraph, mlSources, mlDestinations); }
public double getDistance() { if (distance == -1 && geometry != null) { DistanceCalc dc = new DistanceCalcEarth(); distance = 0.0; Coordinate[] coords = geometry.getCoordinates(); for (int i = 0; i< coords.length - 1; i++) { Coordinate c0 = coords[i]; Coordinate c1 = coords[i+1]; distance += dc.calcDist(c0.y, c0.x, c1.y, c1.x); } } return distance; }
private static int checkRepeatedPoints2d(LineString lineString) { int repeatedPoints = 0; final CoordinateSequence coordSeq = lineString.getCoordinateSequence(); Coordinate nextCoord = null; Coordinate prevCoord; for (int i = 0; i < coordSeq.size(); ++i) { prevCoord = nextCoord; nextCoord = coordSeq.getCoordinate(i); if (nextCoord.equals(prevCoord)) { ++repeatedPoints; } } return repeatedPoints; }
private static void validateLinearRing(LineStringBuilder lineString) { /** * Per GeoJSON spec (http://geojson.org/geojson-spec.html#linestring) * A LinearRing is closed LineString with 4 or more positions. The first and last positions * are equivalent (they represent equivalent points). Though a LinearRing is not explicitly * represented as a GeoJSON geometry type, it is referred to in the Polygon geometry type definition. */ List<Coordinate> points = lineString.coordinates; if (points.size() < 4) { throw new IllegalArgumentException( "invalid number of points in LinearRing (found [" + points.size() + "] - must be >= 4)"); } if (!points.get(0).equals(points.get(points.size() - 1))) { throw new IllegalArgumentException("invalid LinearRing found (coordinates are not closed)"); } }
private static Coordinate[][][] buildCoordinates(List<List<Coordinate[]>> components) { Coordinate[][][] result = new Coordinate[components.size()][][]; for (int i = 0; i < result.length; i++) { List<Coordinate[]> component = components.get(i); result[i] = component.toArray(new Coordinate[component.size()][]); } if(debugEnabled()) { for (int i = 0; i < result.length; i++) { LOGGER.debug("Component [{}]:", i); for (int j = 0; j < result[i].length; j++) { LOGGER.debug("\t{}", Arrays.toString(result[i][j])); } } } return result; }
public void testParseSimplePoint() throws IOException { XContentBuilder pointGeoJson = XContentFactory.jsonBuilder() .startObject() .field("type", "Point") .startArray("coordinates").value(100.0).value(0.0).endArray() .endObject(); Point expected = GEOMETRY_FACTORY.createPoint(new Coordinate(100.0, 0.0)); assertGeometryEquals(new JtsPoint(expected, SPATIAL_CONTEXT), pointGeoJson); }
private PolygonBuilder getPolygonBuilder(GeoPolygon geoPolygon) { List<Coordinate> shell = geoPolygon.getOuterBoundary().stream() .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude())) .collect(Collectors.toList()); PolygonBuilder polygonBuilder = ShapeBuilders.newPolygon(shell); geoPolygon.getHoles().forEach(hole -> { List<Coordinate> coordinates = hole.stream() .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude())) .collect(Collectors.toList()); polygonBuilder.hole(ShapeBuilders.newLineString(coordinates)); }); return polygonBuilder; }
/** * Creates a deep copy of the Object * * @return The deep copy */ public Object clone() { Coordinate[] cloneCoordinates = new Coordinate[size()]; for (int i = 0; i < coordinates.length; i++) { cloneCoordinates[i] = (Coordinate) coordinates[i].clone(); } return new DefaultCoordinateSequence(cloneCoordinates, size); }
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; }
public static String formatCoordinate(Coordinate coord, String separator, StringBuffer buffer) { buffer.setLength(0); DoubleFormatUtil.formatDouble(coord.x, 7, 8, buffer); String xValue = buffer.toString(); buffer.setLength(0); DoubleFormatUtil.formatDouble(coord.y, 7, 8, buffer); return xValue + separator + buffer.toString(); }
/** * 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 void renderPolygon(OpenGLContext context,float zoomWidth,float zoomHeight,Coordinate[] coordinates,float size,Color color){ GL2 gl = context.getGL().getGL2(); float[] c = color.brighter().getColorComponents(null); gl.glColor3f(c[0], c[1], c[2]); gl.glPointSize(size); gl.glBegin(GL.GL_LINE_STRIP); for (Coordinate point : coordinates) { gl.glVertex2d((point.x - context.getX()) / zoomWidth, 1 - (point.y - context.getY()) / zoomHeight); } //Coordinate point = temp.getCoordinates()[0]; //gl.glVertex2d((point.x - x) / width, 1 - (point.y - y) / height); gl.glEnd(); gl.glFlush(); }
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; }
/** * * @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); } }
/** * Creates a new {@code Polygon} whose exterior shell is a smoothed * version of the input {@code Polygon}. * <p> * Note: this method presently ignores holes. * * @param p the input {@code Polygon} * * @param alpha a value between 0 and 1 (inclusive) specifying the tightness * of fit of the smoothed boundary (0 is loose) * * @return the smoothed {@code Polygon} */ public Polygon smooth(Polygon p, double alpha) { Coordinate[] coords = p.getExteriorRing().getCoordinates(); final int N = coords.length - 1; // first coord == last coord Coordinate[][] controlPoints = getPolygonControlPoints(coords, N, alpha); List<Coordinate> smoothCoords = new ArrayList<Coordinate>(); double dist; for (int i = 0; i < N; i++) { int next = (i + 1) % N; dist = coords[i].distance(coords[next]); if (dist < control.getMinLength()) { // segment too short - just copy input coordinate smoothCoords.add(new Coordinate(coords[i])); } else { int smoothN = control.getNumVertices(dist); Coordinate[] segment = cubicBezier( coords[i], coords[next], controlPoints[i][1], controlPoints[next][0], smoothN); int copyN = i < N - 1 ? segment.length - 1 : segment.length; for (int k = 0; k < copyN; k++) { smoothCoords.add(segment[k]); } } } LinearRing shell = geomFactory.createLinearRing(smoothCoords.toArray(new Coordinate[0])); return geomFactory.createPolygon(shell, null); }
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; }
/** * * @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 MatrixRequest createMatrixRequest() { MatrixRequest mtxReq = new MatrixRequest(); mtxReq.setProfileType(_profileType); mtxReq.setMetrics(_metric); mtxReq.setUnits(_units); if (_sourceIndex == -1) { mtxReq.setSources(_locations); mtxReq.setDestinations(_locations); } else { mtxReq.setSources(new Coordinate[] { _locations[_sourceIndex] }); int nLocations = _locations.length; Coordinate[] destinations = new Coordinate[nLocations - 1]; int j = 0; for (int i = 0; i < nLocations; ++i) { if (i != _sourceIndex) { destinations[j] = _locations[i]; ++j; } } mtxReq.setDestinations(destinations); } return mtxReq; }
protected void performMove(Point imagePosition, OpenGLContext context) { if (selectedGeometry == null) { //super.mouseClicked(imagePosition, IClickable.BUTTON1, context); if (this.editedPoint == null && selectedGeometry != null) { if (type.equals(GeometryImage.POINT)) { this.editedPoint = selectedGeometry.getCoordinate(); } else if (type.equals(GeometryImage.POLYGON)) { LineString ls = ((Polygon) selectedGeometry).getExteriorRing(); for (int i = 0; i < ls.getNumPoints(); i++) { Coordinate point = ls.getCoordinateN(i); if (Math.abs(imagePosition.x - point.x) < 5 * context.getZoom() && Math.abs(imagePosition.y - point.y) < 5 * context.getZoom()) { this.editedPoint = point; break; } } } if (this.editedPoint == null) { selectedGeometry.geometryChanged(); selectedGeometry = null; } } else { if (selectedGeometry != null) { selectedGeometry.geometryChanged(); } this.editedPoint = null; } } else { selectedGeometry.geometryChanged(); editedPoint = null; selectedGeometry = null; } }
public void testParseMultiDimensionShapes() throws IOException { // multi dimension point XContentBuilder pointGeoJson = XContentFactory.jsonBuilder() .startObject() .field("type", "Point") .startArray("coordinates").value(100.0).value(0.0).value(15.0).value(18.0).endArray() .endObject(); Point expectedPt = GEOMETRY_FACTORY.createPoint(new Coordinate(100.0, 0.0)); assertGeometryEquals(new JtsPoint(expectedPt, SPATIAL_CONTEXT), pointGeoJson); // multi dimension linestring XContentBuilder lineGeoJson = XContentFactory.jsonBuilder() .startObject() .field("type", "LineString") .startArray("coordinates") .startArray().value(100.0).value(0.0).value(15.0).endArray() .startArray().value(101.0).value(1.0).value(18.0).value(19.0).endArray() .endArray() .endObject(); List<Coordinate> lineCoordinates = new ArrayList<>(); lineCoordinates.add(new Coordinate(100, 0)); lineCoordinates.add(new Coordinate(101, 1)); LineString expectedLS = GEOMETRY_FACTORY.createLineString( lineCoordinates.toArray(new Coordinate[lineCoordinates.size()])); assertGeometryEquals(jtsGeom(expectedLS), lineGeoJson); }
@Override public Geometry transformGeometryPixelFromGeo(Geometry geom)throws GeoTransformException { try{ for(Coordinate pos:geom.getCoordinates()){ double[] temp=getPixelFromGeo(pos.x, pos.y); pos.x=temp[0]; pos.y=temp[1]; } return geom; }catch(Exception ge){ throw new GeoTransformException(ge.getMessage()); } }
/** * Constructs a DefaultCoordinateSequence based on the given array (the * array is not copied). * * @param coordinates the coordinate array that will be referenced. */ public DefaultCoordinateSequence(Coordinate[] coordinates, int size) { if (coordinates == null) { throw new IllegalArgumentException("Null coordinate"); } this.coordinates = coordinates; this.size = size; }
@Override public Shape build() { //Could wrap JtsGeometry but probably slower due to conversions to/from JTS in relate() //MultiPoint geometry = FACTORY.createMultiPoint(points.toArray(new Coordinate[points.size()])); List<Point> shapes = new ArrayList<>(coordinates.size()); for (Coordinate coord : coordinates) { shapes.add(SPATIAL_CONTEXT.makePoint(coord.x, coord.y)); } XShapeCollection<Point> multiPoints = new XShapeCollection<>(shapes, SPATIAL_CONTEXT); multiPoints.setPointsOnly(true); return multiPoints; }
/** * Recursive method which parses the arrays of coordinates used to define * Shapes * * @param parser * Parser that will be read from * @return CoordinateNode representing the start of the coordinate tree * @throws IOException * Thrown if an error occurs while reading from the * XContentParser */ private static CoordinateNode parseCoordinates(XContentParser parser) throws IOException { XContentParser.Token token = parser.nextToken(); // Base cases if (token != XContentParser.Token.START_ARRAY && token != XContentParser.Token.END_ARRAY && token != XContentParser.Token.VALUE_NULL) { double lon = parser.doubleValue(); token = parser.nextToken(); double lat = parser.doubleValue(); token = parser.nextToken(); while (token == XContentParser.Token.VALUE_NUMBER) { token = parser.nextToken(); } return new CoordinateNode(new Coordinate(lon, lat)); } else if (token == XContentParser.Token.VALUE_NULL) { throw new IllegalArgumentException("coordinates cannot contain NULL values)"); } List<CoordinateNode> nodes = new ArrayList<>(); while (token != XContentParser.Token.END_ARRAY) { nodes.add(parseCoordinates(parser)); token = parser.nextToken(); } return new CoordinateNode(nodes); }
protected static Coordinate shift(Coordinate coordinate, double dateline) { if (dateline == 0) { return coordinate; } else { return new Coordinate(-2 * dateline + coordinate.x, coordinate.y); } }
/** * Create a connected list of a list of coordinates * * @param points * array of point * @param offset * index of the first point * @param length * number of points * @return Array of edges */ private static Edge[] ring(int component, boolean direction, boolean handedness, Coordinate[] points, int offset, Edge[] edges, int toffset, int length, final AtomicBoolean translated) { // calculate the direction of the points: // find the point a the top of the set and check its // neighbors orientation. So direction is equivalent // to clockwise/counterclockwise final int top = top(points, offset, length); final int prev = (offset + ((top + length - 1) % length)); final int next = (offset + ((top + 1) % length)); boolean orientation = points[offset + prev].x > points[offset + next].x; // OGC requires shell as ccw (Right-Handedness) and holes as cw (Left-Handedness) // since GeoJSON doesn't specify (and doesn't need to) GEO core will assume OGC standards // thus if orientation is computed as cw, the logic will translate points across dateline // and convert to a right handed system // compute the bounding box and calculate range double[] range = range(points, offset, length); final double rng = range[1] - range[0]; // translate the points if the following is true // 1. shell orientation is cw and range is greater than a hemisphere (180 degrees) but not spanning 2 hemispheres // (translation would result in a collapsed poly) // 2. the shell of the candidate hole has been translated (to preserve the coordinate system) boolean incorrectOrientation = component == 0 && handedness != orientation; if ( (incorrectOrientation && (rng > DATELINE && rng != 2*DATELINE)) || (translated.get() && component != 0)) { translate(points); // flip the translation bit if the shell is being translated if (component == 0) { translated.set(true); } // correct the orientation post translation (ccw for shell, cw for holes) if (component == 0 || (component != 0 && handedness == orientation)) { orientation = !orientation; } } return concat(component, direction ^ orientation, points, offset, edges, toffset, length); }
public void testEdgeCases() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") .startObject("properties").startObject("location") .field("type", "geo_shape") .field("tree", "quadtree") .endObject().endObject() .endObject().endObject().string(); client().admin().indices().prepareCreate("test").addMapping("type1", mapping, XContentType.JSON).execute().actionGet(); ensureGreen(); client().prepareIndex("test", "type1", "blakely").setSource(jsonBuilder().startObject() .field("name", "Blakely Island") .startObject("location") .field("type", "polygon") .startArray("coordinates").startArray() .startArray().value(-122.83).value(48.57).endArray() .startArray().value(-122.77).value(48.56).endArray() .startArray().value(-122.79).value(48.53).endArray() .startArray().value(-122.83).value(48.57).endArray() // close the polygon .endArray().endArray() .endObject() .endObject()).setRefreshPolicy(IMMEDIATE).get(); ShapeBuilder query = ShapeBuilders.newEnvelope(new Coordinate(-122.88, 48.62), new Coordinate(-122.82, 48.54)); // This search would fail if both geoshape indexing and geoshape filtering // used the bottom-level optimization in SpatialPrefixTree#recursiveGetNodes. SearchResponse searchResponse = client().prepareSearch("test").setTypes("type1") .setQuery(geoIntersectionQuery("location", query)) .execute().actionGet(); assertSearchResponse(searchResponse); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L)); assertThat(searchResponse.getHits().getHits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("blakely")); }