Beispiel #1
0
  /**
   * Writes any geometry object. This class figures out which geometry representation to write and
   * calls subclasses to actually write the object.
   *
   * @param geometry The geometry to be encoded
   * @return The JSONBuilder with the new geometry
   * @throws JSONException If anything goes wrong
   */
  public JSONBuilder writeGeom(Geometry geometry) throws JSONException {
    this.object();
    this.key("type");
    this.value(getGeometryName(geometry));

    final int geometryType = getGeometryType(geometry);

    if (geometryType != MULTIGEOMETRY) {
      this.key("coordinates");

      switch (geometryType) {
        case POINT:
          Point point = (Point) geometry;
          Coordinate c = point.getCoordinate();
          writeCoordinate(c.x, c.y, c.z);
          break;
        case LINESTRING:
          writeCoordinates(((LineString) geometry).getCoordinateSequence());
          break;
        case MULTIPOINT:
          writeCoordinates(geometry.getCoordinates());
          break;
        case POLYGON:
          writePolygon((Polygon) geometry);

          break;

        case MULTILINESTRING:
          this.array();

          for (int i = 0, n = geometry.getNumGeometries(); i < n; i++) {
            writeCoordinates(((LineString) geometry.getGeometryN(i)).getCoordinateSequence());
          }

          this.endArray();

          break;

        case MULTIPOLYGON:
          this.array();

          for (int i = 0, n = geometry.getNumGeometries(); i < n; i++) {
            writePolygon((Polygon) geometry.getGeometryN(i));
          }

          this.endArray();

          break;
      }
    } else {
      writeGeomCollection((GeometryCollection) geometry);
    }

    return this.endObject();
  }
 private static boolean collectionToMultiPoint(
     Geometry geom, Class<? extends Geometry> targetType, Collection<Geometry> result) {
   if (geom instanceof GeometryCollection && MultiPoint.class == targetType) {
     Point[] points = new Point[geom.getNumGeometries()];
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       points[i] = geom.getGeometryN(i).getCentroid();
     }
     result.add(geomBuilder.factory.createMultiPoint(points));
     return true;
   }
   return false;
 }
  /**
   * converts the collection of holes (LineString) to a List of String
   *
   * @param holeGeometries
   * @return List of holes as LineString
   */
  private List<LineString> convertHolesGeometriesToHoleList(final Geometry holeGeometries) {

    assert holeGeometries != null;

    List<LineString> holeList = new ArrayList<LineString>(holeGeometries.getNumGeometries());

    for (int i = 0; i < holeGeometries.getNumGeometries(); i++) {

      LineString hole = (LineString) holeGeometries.getGeometryN(i);
      holeList.add(hole);
    }
    return holeList;
  }
  /**
   * split intersection segments have interior location at both left and right
   *
   * @param utilSplitLine
   * @param polygon
   * @param holesList
   */
  private void addSplitLineIntoGraph(
      final Geometry utilSplitLine, final Polygon polygon, List<LineString> holesList) {

    // split intersection segments have interior location at both left
    // and right
    Geometry intersectingLineStrings = utilSplitLine.intersection(polygon);

    if (intersectingLineStrings.getNumGeometries() > 1) {
      // If points exist, then remove them.
      intersectingLineStrings = filterLineString(intersectingLineStrings);
    }

    // use the same input used to create hole edges
    Geometry holeCollection =
        intersectingLineStrings
            .getFactory()
            .createMultiLineString(holesList.toArray(new LineString[holesList.size()]));
    Geometry holeGeometries = holeCollection.difference(utilSplitLine);
    insertEdge(
        intersectingLineStrings,
        holeGeometries,
        Location.BOUNDARY,
        Location.INTERIOR,
        Location.INTERIOR);
  }
 private static boolean collectionToMultiLine(
     Geometry geom, Class<? extends Geometry> targetType, Collection<Geometry> result) {
   if (!(geom instanceof Polygon)
       && !(geom instanceof MultiPolygon)
       && (geom instanceof GeometryCollection)
       && MultiLineString.class == targetType) {
     LineString[] geoms = new LineString[geom.getNumGeometries()];
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       geoms[i] =
           geomBuilder.safeCreateGeometry(LineString.class, geom.getGeometryN(i).getCoordinates());
     }
     result.add(geomBuilder.factory.createMultiLineString(geoms));
     return true;
   }
   return false;
 }
  /**
   * Each edge will be built with 2 coordinates.
   *
   * @param intersectingLineStrings The geometry which edges will be based on.
   * @param onLoc position for ON.
   * @param leftLoc position for LEFT.
   * @param rightLoc position for RIGHT.
   */
  private void insertEdge(
      final Geometry intersectingLineStrings,
      final Geometry holeGeometries,
      final int onLoc,
      final int leftLoc,
      final int rightLoc) {

    for (int i = 0; i < intersectingLineStrings.getNumGeometries(); i++) {

      Geometry intersectingSegment = intersectingLineStrings.getGeometryN(i);

      if ((intersectingSegment.getNumPoints() == 2) && !holeGeometries.isEmpty()) {
        // special case, when the line has 2 coordinates and
        // its orientation can't be calculated because it hasn't.
        intersectingSegment = adjustSegmentToHoleDirection(intersectingSegment, holeGeometries);
      }

      Coordinate[] coords = intersectingSegment.getCoordinates();
      for (int j = 0; j < coords.length - 1; j++) {

        final SplitEdge edge =
            SplitEdge.newInstance(coords[j], coords[j + 1], onLoc, leftLoc, rightLoc);

        // add the list that only contains one edge because it will
        // create 2 directedEdge.
        this.graph.addEdge(edge);
      }
    }
  }
 /** Write an Array of "full" Geometries */
 private int estimateGeometryArray(Geometry container) {
   int result = 0;
   for (int i = 0; i < container.getNumGeometries(); i++) {
     result += estimateBytes(container.getGeometryN(i));
   }
   return result;
 }
Beispiel #8
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));
 }
  /**
   * 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;
  }
Beispiel #10
0
 private void addGeometry(Geometry geom) {
   if (geom.getGeometryType().equals("GeometryCollection")) {
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       addGeometry(geom.getGeometryN(i));
     }
   } else {
     toUnite.add(geom);
   }
 }
Beispiel #11
0
 /**
  * Creates an iterator starting at a specified component and vertex in a linear {@link Geometry}
  *
  * @param linearGeom the linear geometry to iterate over
  * @param componentIndex the component to start at
  * @param vertexIndex the vertex to start at
  * @throws IllegalArgumentException if linearGeom is not lineal
  */
 public LinearIterator(Geometry linearGeom, int componentIndex, int vertexIndex) {
   if (!(linearGeom instanceof Lineal))
     throw new IllegalArgumentException("Lineal geometry is required");
   this.linearGeom = linearGeom;
   numLines = linearGeom.getNumGeometries();
   this.componentIndex = componentIndex;
   this.vertexIndex = vertexIndex;
   loadCurrentLine();
 }
Beispiel #12
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;
 }
 private static boolean collectionToPoint(
     Geometry geom, Class<? extends Geometry> targetType, Collection<Geometry> result) {
   if (geom instanceof GeometryCollection && Point.class == targetType) {
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       result.add(geom.getGeometryN(i).getCentroid());
     }
     return true;
   }
   return false;
 }
Beispiel #14
0
 public static boolean test(Point p) {
   if ((p.getX() >= 53.25666000000001
           && p.getY() >= 12.106109999999944
           && p.getX() <= 53.340828000000094
           && p.getY() <= 12.134442999999976)
       || (p.getX() >= 53.011383000000016
           && p.getY() >= 12.13305500000007
           && p.getX() <= 53.11332700000008
           && p.getY() <= 12.181389000000138)
       || (p.getX() >= 52.08305399999995
           && p.getY() >= 12.144721999999945
           && p.getX() <= 52.397217000000126
           && p.getY() <= 12.2469440000001)
       || (p.getX() >= 43.39138799999994
           && p.getY() >= 12.630278000000088
           && p.getX() <= 43.450554000000125
           && p.getY() <= 12.67388699999998)
       || (p.getX() >= 53.325829
           && p.getY() >= 12.30805400000014
           && p.getX() <= 54.47694400000007
           && p.getY() <= 12.717777000000067)
       || (p.getX() >= 42.67527800000005
           && p.getY() >= 13.660000000000082
           && p.getX() <= 42.79721800000005
           && p.getY() <= 13.782775999999956)
       || (p.getX() >= 42.68916300000012
           && p.getY() >= 13.909443000000124
           && p.getX() <= 42.79999500000014
           && p.getY() <= 14.066944000000092)
       || (p.getX() >= 42.55583200000012
           && p.getY() >= 15.270831999999984
           && p.getX() <= 42.65972099999999
           && p.getY() <= 15.458331999999984)
       || (p.getX() >= 42.67999300000008
           && p.getY() >= 12.592776999999955
           && p.getX() <= 53.114441000000056
           && p.getY() <= 18.99934400000012)) {
     byte[] data;
     try {
       data =
           ByteStreams.toByteArray(
               Antarctica.class.getClassLoader().getResourceAsStream("com/country/Yemen.data"));
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
     Geometry geo = Util.convert(data);
     for (int i = 0; i < geo.getNumGeometries(); i++) {
       if (geo.getGeometryN(i).contains(p)) {
         return true;
       }
     }
   }
   return false;
 }
  private static boolean multiPolygonToPolygon(
      Geometry geom, Class<? extends Geometry> targetType, Collection<Geometry> result) {
    if (geom instanceof MultiPolygon && Polygon.class == targetType) {
      for (int j = 0; j < geom.getNumGeometries(); j++) {
        result.add(geom.getGeometryN(j));
      }

      return true;
    }
    return false;
  }
 public boolean acceptGeometry(Geometry geom) {
   if (geom.getGeometryType().equals("GeometryCollection")) {
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       if (acceptGeometry(geom.getGeometryN(i))) {
         return true;
       }
     }
     return false;
   } else {
     return willDrawSimpleGeometry(geom);
   }
 }
 private static boolean multiPolygonToLine(
     Geometry geom, Class<? extends Geometry> targetType, Collection<Geometry> result) {
   if (geom instanceof MultiPolygon && LineString.class == targetType) {
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       if (!polygonToLine(geom.getGeometryN(i), targetType, result))
         throw new RuntimeException(
             "Huh?  multi polygons should only have polygons in them"); //$NON-NLS-1$
     }
     return true;
   }
   return false;
 }
Beispiel #18
0
  private MapDisplayer calculateMapBoundingBox() throws TransformException {
    /* Identify extreme values for the X and Y dimensions
     * among the Geometries in our featureCollection.
     * Note that this is *after* Geometry preparation (cropping and projecting).
     */
    double dataMinX = Double.POSITIVE_INFINITY;
    double dataMinY = Double.POSITIVE_INFINITY;
    double dataMaxX = Double.NEGATIVE_INFINITY;
    double dataMaxY = Double.NEGATIVE_INFINITY;
    FeatureIterator<SimpleFeature> it = featureCollection.features();
    while (it.hasNext()) {
      SimpleFeature feature = it.next();
      Geometry rawGeometry = (Geometry) feature.getDefaultGeometry();
      Geometry geometry = geometryProjector.projectGeometry(rawGeometry);

      for (int gg = 0; gg < geometry.getNumGeometries(); gg++) {
        Geometry subgeometry = geometry.getGeometryN(gg);

        Coordinate[] coordinates = subgeometry.getCoordinates();

        for (Coordinate coordinate : coordinates) {
          if (coordinate.x < dataMinX) {
            dataMinX = coordinate.x;
          }
          if (coordinate.y < dataMinY) {
            dataMinY = coordinate.y;
          }
          if (coordinate.x > dataMaxX) {
            dataMaxX = coordinate.x;
          }
          if (coordinate.y > dataMaxY) {
            dataMaxY = coordinate.y;
          }
        }
      }
    }
    // YOU MUST CLOSE THE ITERATOR!
    it.close();

    // Exaggerate the data range a bit to provide a buffer around it in the map.
    double xRange = dataMaxX - dataMinX;
    double xBufferSize = MAP_BOUNDING_BOX_BUFFER_RATIO * xRange;
    double bufferedDataMinX = dataMinX - xBufferSize;
    double bufferedDataMaxX = dataMaxX + xBufferSize;

    double yRange = dataMaxY - dataMinY;
    double yBufferSize = MAP_BOUNDING_BOX_BUFFER_RATIO * yRange;
    double bufferedDataMinY = dataMinY - yBufferSize;
    double bufferedDataMaxY = dataMaxY + yBufferSize;

    return new MapDisplayer(bufferedDataMinX, bufferedDataMinY, bufferedDataMaxX, bufferedDataMaxY);
  }
  static Geometry densify(Geometry geom, CoordinateReferenceSystem crs, double maxAreaError)
      throws FactoryException, TransformException {
    // basic checks
    if (maxAreaError <= 0) {
      throw new IllegalArgumentException("maxAreaError must be greater than 0");
    }
    if (!(geom instanceof Polygon) && !(geom instanceof MultiPolygon)) {
      throw new IllegalArgumentException("Geom must be poligonal");
    }
    if (crs == null) {
      throw new IllegalArgumentException("CRS cannot be set to null");
    }
    double previousArea = 0.0;
    CoordinateReferenceSystem targetCRS = CRS.parseWKT(ECKERT_IV_WKT);
    MathTransform firstTransform = CRS.findMathTransform(crs, targetCRS);
    GeometryFactory geomFactory = new GeometryFactory();
    int ngeom = geom.getNumGeometries();
    Geometry densifiedGeometry = geom;
    double areaError = 1.0d;
    int maxIterate = 0;
    do {
      double max = 0;
      maxIterate++;
      // check the maximum side length of the densifiedGeometry
      for (int j = 0; j < ngeom; j++) {
        Geometry geometry = densifiedGeometry.getGeometryN(j);
        Coordinate[] coordinates = geometry.getCoordinates();
        int n = coordinates.length;
        for (int i = 0; i < (n - 1); i++) {
          Coordinate[] coords = new Coordinate[2];
          coords[0] = coordinates[i];
          coords[1] = coordinates[i + 1];
          LineString lineString = geomFactory.createLineString(coords);
          if (lineString.getLength() > max) max = lineString.getLength();
        }
      }

      // calculate the denified geometry
      densifiedGeometry = Densifier.densify(densifiedGeometry, max / 2);

      // reproject densifiedGeometry to Eckert IV
      Geometry targetGeometry = JTS.transform(densifiedGeometry, firstTransform);
      double nextArea = targetGeometry.getArea();

      // evaluate the current error
      areaError = Math.abs(previousArea - nextArea) / nextArea;
      //      logger3.info("AREA ERROR"+areaError);
      previousArea = nextArea;
      // check whether the current error is greater than the maximum allowed
    } while (areaError > maxAreaError && maxIterate < 10);
    return densifiedGeometry;
  }
 private static boolean collectionToMultiPolygon(
     Geometry geom, Class<? extends Geometry> targetType, Collection<Geometry> result) {
   if (!(geom instanceof Polygon)
       && geom instanceof GeometryCollection
       && MultiPolygon.class == targetType) {
     for (int i = 0; i < geom.getNumGeometries(); i++) {
       result.add(
           geomBuilder.safeCreateGeometry(targetType, geom.getGeometryN(i).getCoordinates()));
     }
     return true;
   }
   return false;
 }
  /**
   * @param toSplit the line to split
   * @param line the line to use for the split
   * @return a sorted list of geometries as a result of splitting toSplit with line
   */
  protected List<LineString> splitLine(Geometry toSplit, Geometry line) {
    List<LineString> output = new ArrayList();
    Geometry lines = toSplit.union(line);

    for (int i = 0; i < lines.getNumGeometries(); i++) {
      LineString l = (LineString) lines.getGeometryN(i);
      // TODO to be tested
      if (toSplit.contains(l.getInteriorPoint())) {
        output.add(l);
      }
    }
    geometrySorter(output);
    return output;
  }
  /**
   * @param poly the polygon to split
   * @param line the line to use for the split
   * @return a sorted list of geometries as a result of splitting poly with line
   */
  protected List<Polygon> splitPolygon(Geometry poly, Geometry line) {
    List<Polygon> output = new ArrayList();

    Geometry nodedLinework = poly.getBoundary().union(line);
    Geometry polys = polygonize(nodedLinework);

    // only keep polygons which are inside the input
    for (int i = 0; i < polys.getNumGeometries(); i++) {
      Polygon candpoly = (Polygon) polys.getGeometryN(i);
      if (poly.contains(candpoly.getInteriorPoint())) {
        output.add(candpoly);
      }
    }
    geometrySorter(output);
    return output;
  }
  public void addOSMEdgeToSpatialIndex(OSMEdge osmEdge) {
    // System.out.println("added edge with ID " + osmEdge.getId());
    // counter__edge.put(osmEdge.getId(), osmEdge.getGeometry());	// store edges in the hash map

    Geometry env = osmEdge.getGeometry().getBoundary();
    //  (minx, miny), (maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny).

    if (env.getNumGeometries() > 0) {
      Point p1 = (Point) env.getGeometryN(0);
      Point p2 = (Point) env.getGeometryN(1);

      si.add(
          new Rectangle((float) p1.getX(), (float) p1.getY(), (float) p2.getX(), (float) p2.getY()),
          osmEdge.getId());
    }
  }
  private void setCurrentFeature(final Feature feature) {
    this.feature = feature;
    this.geometry = null;
    this.subGeometries.clear();

    if (feature != null) {
      this.geometry = helper.toObjectiveCRS(feature);
      if (geometry != null) {
        geometry.clone();
        multipolygon = (geometry instanceof MultiPolygon);
        for (int i = 0; i < geometry.getNumGeometries(); i++) {
          subGeometries.add(geometry.getGeometryN(i));
        }
      }
    }
    decoration.setGeometries(Collections.singleton(this.geometry));
  }
  /**
   * Finds the hole that intersects in two points with the the segment.
   *
   * @param splitLineSegment
   * @param holeGeometries
   * @return the hole that intersect with the segment, null in other case
   */
  private LineString intersectionHole(
      final Geometry splitLineSegment, final Geometry holeGeometries) {

    List<LineString> holeList = convertHolesGeometriesToHoleList(holeGeometries);

    LineString intersectedHole = null;

    for (LineString hole : holeList) {
      // Seeks if the segment intersect with the line
      Geometry intersectionWithHole = splitLineSegment.intersection(hole);
      if (intersectionWithHole.getNumGeometries() == 2) {
        intersectedHole = hole;
      }
    }

    return intersectedHole;
  }
  /**
   * Adds the geometries present in the intersection result if they are {@link LineString} into the
   * geometry list
   *
   * @param intersectResult
   * @param geometryList
   * @return the geometry list updated with the geometries intersection
   */
  private List<Geometry> addLinesInCommon(Geometry intersectResult, List<Geometry> geometryList) {

    if (intersectResult instanceof GeometryCollection) {
      // get the lineString or multiLineString instances
      for (int i = 0; i < intersectResult.getNumGeometries(); i++) {

        Geometry part = intersectResult.getGeometryN(i);
        if (part instanceof LineString || part instanceof MultiLineString) {
          geometryList.add(part);
        }
      }
    } else if (intersectResult instanceof LineString
        || intersectResult instanceof MultiLineString) {
      geometryList.add(intersectResult);
    }
    return geometryList;
  }
  /**
   * Computes the angle from the first point to the last point of a LineString or MultiLineString.
   * TODO: put this method into org.opentripplanner.common.geometry.DirectionUtils
   *
   * @param geometry a LineString or a MultiLineString
   * @return
   */
  public synchronized double getFirstToLastSegmentAngle(Geometry geometry) {
    LineString line;
    if (geometry instanceof MultiLineString) {
      line = (LineString) geometry.getGeometryN(geometry.getNumGeometries() - 1);
    } else {
      assert geometry instanceof LineString;
      line = (LineString) geometry;
    }
    int numPoints = line.getNumPoints();
    Coordinate coord0 = line.getCoordinateN(0);
    Coordinate coord1 = line.getCoordinateN(numPoints - 1);
    int i = numPoints - 3;
    while (distanceLibrary.fastDistance(coord0, coord1) < 10 && i >= 0) {
      coord1 = line.getCoordinateN(i--);
    }

    geodeticCalculator.setStartingGeographicPoint(coord0.x, coord0.y);
    geodeticCalculator.setDestinationGeographicPoint(coord1.x, coord1.y);
    return geodeticCalculator.getAzimuth() * Math.PI / 180;
  }
  /**
   * Only return the lines contained on the given geometry, the non lines geometry are rejected.
   *
   * @param geometry Intersection geometry between split line and source geometry.
   * @return The valid geometries needed for the graph, those are lines and multiLines.
   */
  private Geometry filterLineString(Geometry geometry) {

    List<Geometry> filteredLines = new ArrayList<Geometry>();
    for (int i = 0; i < geometry.getNumGeometries(); i++) {

      Geometry possibleLine = geometry.getGeometryN(i);

      // if there are point geometries, discard it.
      if (possibleLine instanceof LineString || possibleLine instanceof MultiLineString) {

        // also remove very very short liens.
        if (possibleLine.getLength() > UsefulSplitLineBuilder.DEPRECIATE_VALUE) {

          filteredLines.add(possibleLine);
        }
      }
    }
    GeometryFactory gf = geometry.getFactory();

    return gf.buildGeometry(filteredLines);
  }
 @Override
 public void filter(Geometry gmtr) {
   if (MultiPolygon.class.isAssignableFrom(binding)) {
     if (gmtr.getArea() != 0.0d && gmtr.getGeometryType().equals("Polygon")) {
       collection.add(gmtr);
     }
   }
   if (MultiLineString.class.isAssignableFrom(binding)) {
     if (gmtr.getLength() != 0.0d && gmtr.getGeometryType().equals("LineString")) {
       collection.add(gmtr);
     }
   }
   if (MultiPoint.class.isAssignableFrom(binding)) {
     if (gmtr.getNumGeometries() > 0 && gmtr.getGeometryType().equals("Point")) {
       collection.add(gmtr);
     }
   }
   if (Point.class.isAssignableFrom(binding)) {
     if (gmtr.getGeometryType().equals("Point")) {
       collection.add(gmtr);
     }
   }
 }
 public static boolean test(Point p) {
   if ((p.getX() >= 105.628998
       && p.getY() >= -10.51097
       && p.getX() <= 105.7519
       && p.getY() <= -10.38408)) {
     byte[] data;
     try {
       data =
           ByteStreams.toByteArray(
               Antarctica.class
                   .getClassLoader()
                   .getResourceAsStream("com/country/ChristmasIsland.data"));
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
     Geometry geo = Util.convert(data);
     for (int i = 0; i < geo.getNumGeometries(); i++) {
       if (geo.getGeometryN(i).contains(p)) {
         return true;
       }
     }
   }
   return false;
 }