Ejemplo n.º 1
0
  /**
   * Fits screen to specified geometry bounds.
   *
   * @param aArea A geometry in geo coordinates space.
   * @throws Exception
   */
  public void fit(Geometry aArea) throws Exception {

    Geometry bounds = aArea.getBoundary();
    Envelope envBounds = bounds.getEnvelopeInternal();
    Point2D.Double leftUpCorner = new Point2D.Double(envBounds.getMinX(), envBounds.getMinY());
    Point2D.Double rightBottomCorner = new Point2D.Double(envBounds.getMaxX(), envBounds.getMaxY());
    Point2D.Double cartlu = geo2Cartesian(leftUpCorner);
    Point2D.Double cartrb = geo2Cartesian(rightBottomCorner);
    double destWidth = Math.abs(cartrb.getX() - cartlu.getX());
    double destHeight = Math.abs(cartrb.getY() - cartlu.getY());
    Coordinate centre =
        new Coordinate((cartrb.getX() + cartlu.getX()) / 2, (cartrb.getY() + cartlu.getY()) / 2);

    Dimension size = getSize();
    Point2D.Double screenLT = awtScreen2Cartesian(new Point(0, 0));
    Point2D.Double screenBR = awtScreen2Cartesian(new Point(size.width, size.height));

    double srcWidth = screenBR.x - screenLT.x;
    double srcHeight = screenBR.y - screenLT.y;
    double sx = srcWidth / destWidth;
    double sy = srcHeight / destHeight;
    double coef = Math.min(sx, sy);
    coef = snapScale(coef);
    scaleView(coef, coef, false);

    Point2D.Double projectedScreenCenter = screen2Cartesian(new Point(0, 0));
    translateView(projectedScreenCenter.x - centre.x, projectedScreenCenter.y - centre.y, true);
    repaint();
  }
Ejemplo n.º 2
0
 /**
  * Returns the nth geometry of a geometry collection, or the geometry if the input is not a
  * collection.
  *
  * @param node xml element containing gml object(s)
  * @param number integer number as the index of nth geometry
  * @return geometry as a gml element
  * @throws QueryException query exception
  */
 @Deterministic
 public ANode geometryN(final ANode node, final Int number) throws QueryException {
   final Geometry geo = checkGeo(node);
   final long n = number.itr();
   if (n < 1 || n > geo.getNumGeometries()) throw GeoErrors.outOfRangeIdx(number);
   return gmlWriter(geo.getGeometryN((int) n - 1));
 }
Ejemplo n.º 3
0
 /**
  * Returns a boolean value that shows if whether relationships between the boundaries, interiors
  * and exteriors of two geometries match the pattern specified in intersection-matrix-pattern.
  *
  * @param node1 xml element containing gml object(s)
  * @param node2 xml element containing gml object(s)
  * @param intersectionMatrix intersection matrix for two geometries
  * @return boolean value
  * @throws QueryException query exception
  */
 @Deterministic
 public Bln relate(final ANode node1, final ANode node2, final Str intersectionMatrix)
     throws QueryException {
   final Geometry geo1 = checkGeo(node1);
   final Geometry geo2 = checkGeo(node2);
   return Bln.get(geo1.relate(geo2, intersectionMatrix.toJava()));
 }
Ejemplo n.º 4
0
  private FeatureCollection convexHhull(TaskMonitor monitor, FeatureCollection fc) {
    monitor.allowCancellationRequests();
    monitor.report(I18N.get("ui.plugin.analysis.ConvexHullPlugIn.Computing-Convex-Hull") + "...");

    int size = fc.size();
    GeometryFactory geomFact = null;

    if (size == 0) {
      return null;
    }
    int count = 0;
    Geometry[] geoms = new Geometry[size];

    for (Iterator i = fc.iterator(); i.hasNext(); ) {
      Feature f = (Feature) i.next();
      Geometry geom = f.getGeometry();
      if (geom == null) {
        continue;
      }
      if (geomFact == null) {
        geomFact = geom.getFactory();
      }

      geoms[count++] = geom;
    }
    GeometryCollection gc = geomFact.createGeometryCollection(geoms);
    Geometry hull = gc.convexHull();
    List hullList = new ArrayList();
    hullList.add(hull);

    return FeatureDatasetFactory.createFromGeometry(hullList);
  }
Ejemplo n.º 5
0
  protected Geometry transformPolygon(Polygon geom, Geometry parent) {
    boolean isAllValidLinearRings = true;
    Geometry shell = transformLinearRing((LinearRing) geom.getExteriorRing(), geom);

    if (shell == null || !(shell instanceof LinearRing) || shell.isEmpty())
      isAllValidLinearRings = false;
    // return factory.createPolygon(null, null);

    ArrayList holes = new ArrayList();
    for (int i = 0; i < geom.getNumInteriorRing(); i++) {
      Geometry hole = transformLinearRing((LinearRing) geom.getInteriorRingN(i), geom);
      if (hole == null || hole.isEmpty()) {
        continue;
      }
      if (!(hole instanceof LinearRing)) isAllValidLinearRings = false;

      holes.add(hole);
    }

    if (isAllValidLinearRings)
      return factory.createPolygon(
          (LinearRing) shell, (LinearRing[]) holes.toArray(new LinearRing[] {}));
    else {
      List components = new ArrayList();
      if (shell != null) components.add(shell);
      components.addAll(holes);
      return factory.buildGeometry(components);
    }
  }
Ejemplo n.º 6
0
 public static void main(String[] args) throws NumberFormatException, IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   int numberOfCases = 0, numberOfNails = 0;
   double initialLength = 0.0;
   numberOfCases = Integer.parseInt(in.readLine());
   StringBuilder builder = new StringBuilder();
   while (numberOfCases-- > 0) {
     StringTokenizer tokenizer = new StringTokenizer(in.readLine());
     initialLength = Double.parseDouble(tokenizer.nextToken());
     numberOfNails = Integer.parseInt(tokenizer.nextToken());
     ArrayList<Geometry.Point> allPoints = new ArrayList<Geometry.Point>();
     double x = 0, y = 0;
     for (int i = 0; i < numberOfNails; ++i) {
       tokenizer = new StringTokenizer(in.readLine());
       x = Double.parseDouble(tokenizer.nextToken());
       y = Double.parseDouble(tokenizer.nextToken());
       Geometry.Point toAdd = new Geometry.Point(x, y);
       allPoints.add(toAdd);
     }
     ArrayList<Geometry.Point> convex = Geometry.chull(allPoints);
     String toAppend =
         String.format("%.5f\n", Math.max(initialLength, Geometry.perimeter(convex)));
     builder.append(toAppend);
     in.readLine(); // EXTRA line
   }
   System.out.printf(builder.toString());
 }
Ejemplo n.º 7
0
  @Override
  public void reset() throws SQLException {
    cellI = 0;
    cellJ = 0;
    firstRow = false;
    // We compute the extend according the first input value
    if (isTable) {
      Statement statement = connection.createStatement();
      ResultSet rs =
          statement.executeQuery(
              "select ST_Extent("
                  + getFirstGeometryField(tableName, connection)
                  + ")  from "
                  + tableName);
      try {
        rs.next();
        Geometry geomExtend = (Geometry) rs.getObject(1);
        if (geomExtend == null) {
          throw new SQLException("The envelope cannot be null.");
        } else {
          envelope = geomExtend.getEnvelopeInternal();
          initParameters();
        }

      } finally {
        rs.close();
      }
    } else {
      if (envelope == null) {
        throw new SQLException("The input geometry used to compute the grid cannot be null.");
      } else {
        initParameters();
      }
    }
  }
Ejemplo n.º 8
0
  private GeometryCollection editGeometryCollection(
      GeometryCollection collection, GeometryEditorOperation operation) {
    // first edit the entire collection
    // MD - not sure why this is done - could just check original collection?
    GeometryCollection collectionForType = (GeometryCollection) operation.edit(collection, factory);

    // edit the component geometries
    ArrayList geometries = new ArrayList();
    for (int i = 0; i < collectionForType.getNumGeometries(); i++) {
      Geometry geometry = edit(collectionForType.getGeometryN(i), operation);
      if (geometry == null || geometry.isEmpty()) {
        continue;
      }
      geometries.add(geometry);
    }

    if (collectionForType.getClass() == MultiPoint.class) {
      return factory.createMultiPoint((Point[]) geometries.toArray(new Point[] {}));
    }
    if (collectionForType.getClass() == MultiLineString.class) {
      return factory.createMultiLineString((LineString[]) geometries.toArray(new LineString[] {}));
    }
    if (collectionForType.getClass() == MultiPolygon.class) {
      return factory.createMultiPolygon((Polygon[]) geometries.toArray(new Polygon[] {}));
    }
    return factory.createGeometryCollection((Geometry[]) geometries.toArray(new Geometry[] {}));
  }
  private void makePartialCylinder(
      DrawContext dc,
      double radius,
      double[] altitudes,
      boolean[] terrainConformant,
      int slices,
      int stacks,
      int orientation,
      double start,
      double sweep,
      Vec4 referenceCenter,
      Geometry dest) {
    GeometryBuilder gb = this.getGeometryBuilder();
    gb.setOrientation(orientation);
    float height = (float) (altitudes[1] - altitudes[0]);

    int count = gb.getPartialCylinderVertexCount(slices, stacks);
    int numCoords = 3 * count;
    float[] verts = new float[numCoords];
    float[] norms = new float[numCoords];
    gb.makePartialCylinderVertices(
        (float) radius, height, slices, stacks, (float) start, (float) sweep, verts);
    gb.makePartialCylinderNormals(
        (float) radius, height, slices, stacks, (float) start, (float) sweep, norms);
    this.makePartialCylinderTerrainConformant(
        dc, slices, stacks, verts, altitudes, terrainConformant, referenceCenter);

    dest.setVertexData(count, verts);
    dest.setNormalData(count, norms);
  }
  private void makeRadialWall(
      DrawContext dc,
      double[] radii,
      double angle,
      double[] altitudes,
      boolean[] terrainConformant,
      int pillars,
      int stacks,
      int orientation,
      Vec4 referenceCenter,
      Geometry dest) {
    GeometryBuilder gb = this.getGeometryBuilder();
    gb.setOrientation(orientation);
    float height = (float) (altitudes[1] - altitudes[0]);

    int count = gb.getRadialWallVertexCount(pillars, stacks);
    int numCoords = 3 * count;
    float[] verts = new float[numCoords];
    float[] norms = new float[numCoords];
    gb.makeRadialWallVertices(
        (float) radii[0], (float) radii[1], height, (float) angle, pillars, stacks, verts);
    this.makeRadialWallTerrainConformant(
        dc, pillars, stacks, verts, altitudes, terrainConformant, referenceCenter);
    gb.makeRadialWallNormals(
        (float) radii[0], (float) radii[1], height, (float) angle, pillars, stacks, norms);

    dest.setVertexData(count, verts);
    dest.setNormalData(count, norms);
  }
Ejemplo n.º 11
0
  /**
   * Returns the z-coordinate value for point.
   *
   * @param node xml element containing gml object(s)
   * @return z double value
   * @throws QueryException query exception
   */
  @Deterministic
  public Dbl z(final ANode node) throws QueryException {
    final Geometry geo = geo(node, Q_GML_POINT);
    if (geo == null && checkGeo(node) != null)
      throw GeoErrors.geoType(node.qname().local(), "Line");

    return Dbl.get(geo.getCoordinate().z);
  }
 protected int getGeometryType(Geometry geometry) {
   WkbGeometryType type = WkbGeometryType.forClass(geometry.getClass());
   if (type == null)
     throw new UnsupportedConversionException(
         String.format(
             "Can't convert geometries of type %s", geometry.getClass().getCanonicalName()));
   return type.getTypeCode();
 }
 static double area(Collection geoms) {
   double area = 0.0;
   for (Iterator i = geoms.iterator(); i.hasNext(); ) {
     Geometry geom = (Geometry) i.next();
     area += geom.getArea();
   }
   return area;
 }
  /**
   * Tests whether a geometry consists of a single polygon with no holes.
   *
   * @return true if the geometry is a single polygon with no holes
   */
  private boolean isSingleShell(Geometry geom) {
    // handles single-element MultiPolygons, as well as Polygons
    if (geom.getNumGeometries() != 1) return false;

    Polygon poly = (Polygon) geom.getGeometryN(0);
    int numHoles = poly.getNumInteriorRing();
    if (numHoles == 0) return true;
    return false;
  }
 @Test
 public void polygonWithoutHolesSerializerTest() throws Exception {
   Geometry polygon = reader.read("POLYGON ((35 10, 10 20, 15 40," + " 45 45, 35 10))");
   polygon.setSRID(4326);
   String polygonGeoJsonString = mapper.writeValueAsString(polygon);
   logger.info(":::::::::::::::::::::::GEO_JSON_POLYGON : \n{}\n", polygonGeoJsonString);
   org.geojson.Polygon p = mapper.readValue(polygonGeoJsonString, org.geojson.Polygon.class);
   mapper.writeValue(new File("./target/PolygonWithoutHoles.json"), p);
 }
Ejemplo n.º 16
0
 public Geometry act(Geometry lhs, Geometry rhs) throws GeometricFailure {
   Map<Symbol, MDouble> rhs_values = rhs.values();
   Map<Symbol, MDouble> lhs_values = lhs.values();
   for (Map.Entry<Symbol, Symbol> tuple : lhs.join(rhs).entrySet()) {
     MDouble this_rhs_value = rhs_values.get(tuple.getValue());
     this_rhs_value.set(action(lhs_values.get(tuple.getKey()).get(), this_rhs_value.get()));
   }
   return rhs;
 }
Ejemplo n.º 17
0
 public Geometry GetSpatialFilter() {
   long cPtr = ogrJNI.Layer_GetSpatialFilter(swigCPtr, this);
   Geometry ret = null;
   if (cPtr != 0) {
     ret = new Geometry(cPtr, false);
     ret.addReference(this);
   }
   return ret;
 }
Ejemplo n.º 18
0
 private static Polygon findPolygonContaining(Geometry geom, Coordinate pt) {
   PointLocator locator = new PointLocator();
   for (int i = 0; i < geom.getNumGeometries(); i++) {
     Polygon poly = (Polygon) geom.getGeometryN(i);
     int loc = locator.locate(pt, poly);
     if (loc == Location.INTERIOR) return poly;
   }
   return null;
 }
 static List findIntersecting(Collection targetGeoms, Geometry queryGeom) {
   List result = new ArrayList();
   for (Iterator it = targetGeoms.iterator(); it.hasNext(); ) {
     Geometry test = (Geometry) it.next();
     if (test.intersects(queryGeom)) {
       result.add(test);
     }
   }
   return result;
 }
 @Test
 public void multiPointSerializerTest() throws Exception {
   Geometry multiPoint = reader.read("MULTIPOINT ((10 40), (40 30), " + "(20 20), (30 10))");
   multiPoint.setSRID(4326);
   String multiPointGeoJsonString = mapper.writeValueAsString(multiPoint);
   logger.info(":::::::::::::::::::::::GEO_JSON_MULTI_POINT : \n{}\n", multiPointGeoJsonString);
   org.geojson.MultiPoint multiPointGeoJson =
       mapper.readValue(multiPointGeoJsonString, org.geojson.MultiPoint.class);
   mapper.writeValue(new File("./target/MultiPoint.json"), multiPointGeoJson);
 }
Ejemplo n.º 21
0
  /**
   * Edit the input {@link Geometry} with the given edit operation. Clients can create subclasses of
   * {@link GeometryEditorOperation} or {@link CoordinateOperation} to perform required
   * modifications.
   *
   * @param geometry the Geometry to edit
   * @param operation the edit operation to carry out
   * @return a new {@link Geometry} which is the result of the editing (which may be empty)
   */
  public Geometry edit(Geometry geometry, GeometryEditorOperation operation) {
    // nothing to do
    if (geometry == null) return null;

    Geometry result = editInternal(geometry, operation);
    if (isUserDataCopied) {
      result.setUserData(geometry.getUserData());
    }
    return result;
  }
Ejemplo n.º 22
0
 private String geometrySignature(Geometry geom) {
   if (geom == null) return "";
   String sig = geom.getGeometryType();
   if (geom instanceof GeometryCollection) {
     sig += "[" + geom.getNumGeometries() + "]";
   } else {
     sig += "(" + geom.getNumPoints() + ")";
   }
   return sig;
 }
Ejemplo n.º 23
0
 protected Geometry transformMultiPolygon(MultiPolygon geom, Geometry parent) {
   List transGeomList = new ArrayList();
   for (int i = 0; i < geom.getNumGeometries(); i++) {
     Geometry transformGeom = transformPolygon((Polygon) geom.getGeometryN(i), geom);
     if (transformGeom == null) continue;
     if (transformGeom.isEmpty()) continue;
     transGeomList.add(transformGeom);
   }
   return factory.buildGeometry(transGeomList);
 }
Ejemplo n.º 24
0
 /**
  * Removes the common coordinate bits from a Geometry. The coordinates of the Geometry are
  * changed.
  *
  * @param geom the Geometry from which to remove the common coordinate bits
  * @return the shifted Geometry
  */
 public Geometry removeCommonBits(Geometry geom) {
   if (commonCoord.x == 0.0 && commonCoord.y == 0.0) return geom;
   Coordinate invCoord = new Coordinate(commonCoord);
   invCoord.x = -invCoord.x;
   invCoord.y = -invCoord.y;
   Translater trans = new Translater(invCoord);
   geom.apply(trans);
   geom.geometryChanged();
   return geom;
 }
Ejemplo n.º 25
0
  public static List extractElements(Geometry geom, boolean skipEmpty) {
    List elem = new ArrayList();
    if (geom == null) return elem;

    for (int i = 0; i < geom.getNumGeometries(); i++) {
      Geometry elemGeom = geom.getGeometryN(i);
      if (skipEmpty && elemGeom.isEmpty()) continue;
      elem.add(elemGeom);
    }
    return elem;
  }
  public double measure(Geometry g1, Geometry g2) {
    double distance = DiscreteHausdorffDistance.distance(g1, g2, DENSIFY_FRACTION);

    Envelope env = new Envelope(g1.getEnvelopeInternal());
    env.expandToInclude(g2.getEnvelopeInternal());
    double envSize = diagonalSize(env);
    // normalize so that more similarity produces a measure closer to 1
    double measure = 1 - distance / envSize;

    // System.out.println("Hausdorff distance = " + distance + ", measure = " + measure);
    return measure;
  }
Ejemplo n.º 27
0
 /**
  * recursively visit the subgraph and unbatch geometries
  *
  * @param s
  */
 private void unbatchSubGraph(Spatial s) {
   if (s instanceof Node) {
     for (Spatial sp : ((Node) s).getChildren()) {
       unbatchSubGraph(sp);
     }
   } else if (s instanceof Geometry) {
     Geometry g = (Geometry) s;
     if (g.isBatched()) {
       g.unBatch();
     }
   }
 }
Ejemplo n.º 28
0
  /**
   * Returns the nth point of a line.
   *
   * @param node xml element containing gml object(s)
   * @param number index of i-th point
   * @return n-th point as a gml element
   * @throws QueryException query exception
   */
  @Deterministic
  public ANode pointN(final ANode node, final Int number) throws QueryException {
    final Geometry geo = geo(node, Q_GML_LINEARRING, Q_GML_LINESTRING);
    if (geo == null && checkGeo(node) != null)
      throw GeoErrors.geoType(node.qname().local(), "Line");

    final int max = geo.getNumPoints();
    final long n = number.itr();
    if (n < 1 || n > max) throw GeoErrors.outOfRangeIdx(number);

    return gmlWriter(((LineString) geo).getPointN((int) n - 1));
  }
Ejemplo n.º 29
0
 public void testEquals10() throws Exception {
   WKTReader reader = new WKTReader(new GeometryFactory(new PrecisionModel(1), 0));
   Geometry l1 =
       reader.read(
           "POLYGON((1732328800 519578384, 1732026179 519976285, 1731627364 519674014, 1731929984 519276112, 1732328800 519578384))");
   Geometry l2 =
       reader.read(
           "POLYGON((1731627364 519674014, 1731929984 519276112, 1732328800 519578384, 1732026179 519976285, 1731627364 519674014))");
   l1.normalize();
   l2.normalize();
   assertTrue(l1.equalsExact(l2));
 }
Ejemplo n.º 30
0
 protected Geometry transformGeometryCollection(GeometryCollection geom, Geometry parent) {
   List transGeomList = new ArrayList();
   for (int i = 0; i < geom.getNumGeometries(); i++) {
     Geometry transformGeom = transform(geom.getGeometryN(i));
     if (transformGeom == null) continue;
     if (pruneEmptyGeometry && transformGeom.isEmpty()) continue;
     transGeomList.add(transformGeom);
   }
   if (preserveGeometryCollectionType)
     return factory.createGeometryCollection(GeometryFactory.toGeometryArray(transGeomList));
   return factory.buildGeometry(transGeomList);
 }