/** {@inheritDoc } */
  @Override
  public boolean evaluate(final Object object) {
    Geometry leftGeom = toGeometry(object, left);
    Geometry rightGeom = toGeometry(object, right);

    if (leftGeom == null || rightGeom == null) {
      return false;
    }

    final Geometry[] values;
    try {
      values = toSameCRS(leftGeom, rightGeom);
    } catch (FactoryException | TransformException ex) {
      Logging.getLogger("org.geotoolkit.filter.binaryspatial").log(Level.WARNING, null, ex);
      return false;
    }
    leftGeom = values[0];
    rightGeom = values[1];

    final Envelope envLeft = leftGeom.getEnvelopeInternal();
    final Envelope envRight = rightGeom.getEnvelopeInternal();

    if (envLeft.intersects(envRight)) {
      return leftGeom.overlaps(rightGeom);
    }

    return false;
  }
 @Override
 public BoundingBox getBounds() {
   // Calculate bounds?
   //
   if (bounds == null) {
     //
     // Initialize bounds
     //
     bounds = new ReferencedEnvelope(getFeatureType().getCoordinateReferenceSystem());
     //
     // Loop over all geometries
     //
     for (EFeatureGeometry<Geometry> it : eInternal.getGeometryList(Geometry.class)) {
       if (!it.isEmpty()) {
         Geometry g = it.getValue();
         if (bounds.isNull()) {
           bounds.init(g.getEnvelopeInternal());
         } else {
           bounds.expandToInclude(g.getEnvelopeInternal());
         }
       }
     }
   }
   return bounds;
 }
  /** @see org.geotools.data.FeatureStore#setFeatures(org.geotools.data.FeatureReader) */
  public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader)
      throws IOException {
    WFSTransactionState ts = null;

    if (trans == Transaction.AUTO_COMMIT) {
      ts = new WFSTransactionState(ds);
    } else {
      ts = (WFSTransactionState) trans.getState(ds);
    }

    ts.addAction(
        getSchema().getTypeName(), new DeleteAction(getSchema().getTypeName(), Filter.INCLUDE));

    ReferencedEnvelope bounds = null;
    while (reader.hasNext()) {

      try {
        SimpleFeature f = reader.next();
        List<AttributeDescriptor> atrs = f.getFeatureType().getAttributeDescriptors();
        for (int i = 0; i < atrs.size(); i++) {
          if (atrs.get(i) instanceof GeometryDescriptor) {
            Geometry g = (Geometry) f.getAttribute(i);
            CoordinateReferenceSystem cs =
                ((GeometryDescriptor) atrs.get(i)).getCoordinateReferenceSystem();
            if (cs != null && !cs.getIdentifiers().isEmpty())
              g.setUserData(cs.getIdentifiers().iterator().next().toString());
            if (g == null) continue;
            if (bounds == null) {
              bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs);
            } else {
              bounds.expandToInclude(g.getEnvelopeInternal());
            }
          }
        }
        ts.addAction(getSchema().getTypeName(), new InsertAction(f));
      } catch (NoSuchElementException e) {
        WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
      } catch (IllegalAttributeException e) {
        WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
      }
    }

    // Fire a notification.
    // JE
    if (bounds == null) {
      // if bounds are null then send an envelope to say that features were added but
      // at an unknown location.
      bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    } else {
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    }
    if (trans == Transaction.AUTO_COMMIT) {
      ts.commit();
    }
  }
  /**
   * @see org.geotools.data.FeatureStore#modifyFeatures(org.geotools.feature.AttributeType[],
   *     java.lang.Object[], org.geotools.filter.Filter)
   */
  public void modifyFeatures(Name[] names, Object[] value, Filter filter2) throws IOException {
    Filter filter = ds.processFilter(filter2);
    WFSTransactionState ts = null;

    if (trans == Transaction.AUTO_COMMIT) {
      ts = new WFSTransactionState(ds);
    } else {
      ts = (WFSTransactionState) trans.getState(ds);
    }

    Map<String, Object> props = new HashMap<String, Object>();

    ReferencedEnvelope bounds = null;
    for (int i = 0; i < names.length; i++) {
      if (names[i] instanceof GeometryDescriptor) {
        Geometry g = (Geometry) value[i];
        CoordinateReferenceSystem cs =
            ((GeometryDescriptor) names[i]).getCoordinateReferenceSystem();

        if (cs != null && !cs.getIdentifiers().isEmpty())
          g.setUserData(cs.getIdentifiers().iterator().next().toString());
        g.setUserData(cs.getIdentifiers().iterator().next().toString());
        if (cs != null && !cs.getIdentifiers().isEmpty())
          g.setUserData(cs.getIdentifiers().iterator().next().toString());
        // set/expand the bounds that are being changed.
        if (g == null) continue;
        if (bounds == null) {
          bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs);
        } else {
          bounds.expandToInclude(g.getEnvelopeInternal());
        }
      }
      props.put(names[i].getLocalPart(), value[i]);
    }

    ts.addAction(
        getSchema().getTypeName(), new UpdateAction(getSchema().getTypeName(), filter, props));

    // Fire a notification.
    // JE
    if (bounds == null) {
      // if bounds are null then send an envelope to say that features were modified but
      // at an unknown location.
      bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    } else {
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    }

    if (trans == Transaction.AUTO_COMMIT) {
      ts.commit();
    }
  }
  /**
   * Ensure Line crosses the other Line at a node.
   *
   * <p>
   *
   * @param layers a HashMap of key="TypeName" value="FeatureSource"
   * @param envelope The bounding box of modified features
   * @param results Storage for the error and warning messages
   * @return True if no features intersect. If they do then the validation failed.
   * @throws Exception DOCUMENT ME!
   * @see org.geotools.validation.IntegrityValidation#validate(java.util.Map,
   *     com.vividsolutions.jts.geom.Envelope, org.geotools.validation.ValidationResults)
   */
  public boolean validate(Map layers, Envelope envelope, ValidationResults results)
      throws Exception {
    boolean r = true;

    FeatureSource<SimpleFeatureType, SimpleFeature> fsLine =
        (FeatureSource<SimpleFeatureType, SimpleFeature>) layers.get(getLineTypeRef());

    FeatureCollection<SimpleFeatureType, SimpleFeature> fcLine = fsLine.getFeatures();
    FeatureIterator<SimpleFeature> fLine = fcLine.features();

    FeatureSource<SimpleFeatureType, SimpleFeature> fsRLine =
        (FeatureSource<SimpleFeatureType, SimpleFeature>) layers.get(getRestrictedLineTypeRef());

    FeatureCollection<SimpleFeatureType, SimpleFeature> fcRLine = fsRLine.getFeatures();

    while (fLine.hasNext()) {
      SimpleFeature line = fLine.next();
      FeatureIterator<SimpleFeature> fRLine = fcRLine.features();
      Geometry lineGeom = (Geometry) line.getDefaultGeometry();
      if (envelope.contains(lineGeom.getEnvelopeInternal())) {
        // 	check for valid comparison
        if (LineString.class.isAssignableFrom(lineGeom.getClass())) {
          while (fRLine.hasNext()) {
            SimpleFeature rLine = fRLine.next();
            Geometry rLineGeom = (Geometry) rLine.getDefaultGeometry();
            if (envelope.contains(rLineGeom.getEnvelopeInternal())) {
              if (LineString.class.isAssignableFrom(rLineGeom.getClass())) {
                if (lineGeom.intersects(rLineGeom)) {
                  if (!hasPair(
                      ((LineString) lineGeom).getCoordinateSequence(),
                      ((LineString) rLineGeom).getCoordinateSequence())) {
                    results.error(
                        rLine,
                        "Line does not intersect line at node covered by the specified Line.");
                    r = false;
                  }
                } else {
                  results.warning(rLine, "Does not intersect the LineString");
                }
                // do next.
              } else {
                fcRLine.remove(rLine);
                results.warning(
                    rLine, "Invalid type: this feature is not a derivative of a LineString");
              }
            } else {
              fcRLine.remove(rLine);
            }
          }
        } else {
          results.warning(line, "Invalid type: this feature is not a derivative of a LineString");
        }
      }
    }
    return r;
  }
  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;
  }
Exemple #7
0
  public static void getRelationsInfo(List<Geometry> aGeometryList) {

    int numVar = aGeometryList.size();
    int[] numRel = new int[8];
    int sum = 0;
    for (int i1 = 0; i1 < numVar; i1++) {
      Geometry a1 = aGeometryList.get(i1);
      Envelope a1m = a1.getEnvelopeInternal();
      double[] m1 = new double[4];
      m1[0] = a1m.getMinX();
      m1[1] = a1m.getMaxX();
      m1[2] = a1m.getMinY();
      m1[3] = a1m.getMaxY();
      for (int j1 = i1 + 1; j1 < numVar; j1++) {

        Geometry a2 = aGeometryList.get(j1);
        Envelope a2m = a2.getEnvelopeInternal();
        double[] m2 = new double[4];
        m2[0] = a2m.getMinX();
        m2[1] = a2m.getMaxX();
        m2[2] = a2m.getMinY();
        m2[3] = a2m.getMaxY();
        boolean[] relationAB = new boolean[8];
        // assume relation table is indexed by i*n+j for each pair (i,j), i<j
        relationAB = GeometryRelated.computeRCC8RelationMBR(a1, a2, m1, m2);
        if (GeometryRelated.rectangleIntersect(m1, m2)) {
          sum += 2;
        }
        for (int k = 0; k < 8; k++) {
          // we already know relation is basic
          if (relationAB[k]) {
            numRel[k]++;
            break;
          }
        }
      }
    }

    System.out.println("DC number:" + numRel[0]);
    System.out.println("EC number:" + numRel[1]);
    System.out.println("PO number:" + numRel[2]);
    System.out.println("NTPP number:" + numRel[3]);
    System.out.println("TPP number:" + numRel[4]);
    System.out.println("NTPPi number:" + numRel[5]);
    System.out.println("TPPi number:" + numRel[6]);
    System.out.println("EQ number:" + numRel[7]);
    System.out.println("Average Intersection Degree: " + ((double) sum / ((double) numVar)));
  }
  /**
   * Returns all the FeatureId and ID attributes based on the query against the spatial index
   *
   * @return all the FeatureId and ID attributes based on the query against the spatial index
   */
  protected synchronized Map<String, FeatureId> unrefinedSpatialMatches() {
    if (_unrefinedMatches == null) {
      Geometry geom = null;

      // _index.query returns geometries that intersect with provided envelope. To use later a
      // spatial filter that
      // provides geometries that don't intersect with the query envelope (_geom) should be used a
      // full extent
      // envelope in this method, instead of the query envelope (_geom)
      if (getFilter().getClass().getName().equals("org.geotools.filter.spatial.DisjointImpl")) {
        try {
          geom = WORLD_BOUNDS;
        } catch (Exception ex) {
          ex.printStackTrace();
          return _unrefinedMatches;
        }

      } else {
        geom = _geom;
      }

      SpatialIndex spatialIndex = sourceAccessor.two();
      @SuppressWarnings("unchecked")
      List<Pair<FeatureId, String>> fids = spatialIndex.query(geom.getEnvelopeInternal());
      _unrefinedMatches = new HashMap<>();
      for (Pair<FeatureId, String> match : fids) {
        _unrefinedMatches.put(match.two(), match.one());
      }
    }
    return _unrefinedMatches;
  }
Exemple #9
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();
  }
  @Override
  public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
    if (value != null) {
      Wfs20FeatureCollection wfc = (Wfs20FeatureCollection) value;

      String schemaLoc = generateSchemaLocationFromMetacards(wfc.getMembers(), prefixToUriMapping);

      for (Entry<String, String> entry : prefixToUriMapping.entrySet()) {
        writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + entry.getKey(), entry.getValue());
      }
      writer.addAttribute(Wfs20Constants.ATTRIBUTE_SCHEMA_LOCATION, schemaLoc);

      Geometry allGeometry = getBounds(wfc.getMembers());
      if (!allGeometry.isEmpty()) {
        XmlNode.writeEnvelope(
            Wfs20Constants.GML_PREFIX + ":" + "boundedBy",
            context,
            writer,
            allGeometry.getEnvelopeInternal());
      }

      for (Metacard mc : wfc.getMembers()) {
        writer.startNode(Wfs20Constants.GML_PREFIX + ":" + FEATURE_MEMBER);
        context.convertAnother(mc);
        writer.endNode();
      }
    } else {
      LOGGER.warn("Incoming value was null");
    }
  }
Exemple #11
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();
      }
    }
  }
 public synchronized void initIndexes() {
   if (vertexIndex != null) {
     return;
   }
   graphService.setLoadLevel(LoadLevel.DEBUG);
   Graph graph = graphService.getGraph();
   vertexIndex = new STRtree();
   edgeIndex = new STRtree();
   for (Vertex v : graph.getVertices()) {
     Envelope vertexEnvelope = new Envelope(v.getCoordinate());
     vertexIndex.insert(vertexEnvelope, v);
     for (Edge e : v.getOutgoing()) {
       Envelope envelope;
       Geometry geometry = e.getGeometry();
       if (geometry == null) {
         envelope = vertexEnvelope;
       } else {
         envelope = geometry.getEnvelopeInternal();
       }
       edgeIndex.insert(envelope, e);
     }
   }
   vertexIndex.build();
   edgeIndex.build();
 }
 public MCIndexedPointInAreaLocator(Geometry g) {
   areaGeom = g;
   if (!(g instanceof Polygonal)) throw new IllegalArgumentException("Argument must be Polygonal");
   buildIndex(g);
   Envelope env = g.getEnvelopeInternal();
   maxXExtent = env.getMaxX() + 1.0;
 }
Exemple #14
0
 /**
  * Returns the minimal y-value of the given geometry.
  *
  * @param geom Geometry
  * @return The minimal y-value of the given geometry, or null if the geometry is null.
  */
 public static Double getMinY(Geometry geom) {
   if (geom != null) {
     return geom.getEnvelopeInternal().getMinY();
   } else {
     return null;
   }
 }
 @Override
 protected Envelope getEnvelope(final TestGeometry entry) {
   // incorporate the bounding box of the entry's envelope
   final Geometry geometry = entry.geom;
   if ((geometry != null) && !geometry.isEmpty()) {
     return geometry.getEnvelopeInternal();
   }
   return null;
 }
 public static ArrayList<String> getListOfSensors(String envelope) throws ParseException {
   Geometry geom = new WKTReader().read(envelope);
   List listEnvelope = geoIndex.query(geom.getEnvelopeInternal());
   ArrayList<String> sensors = new ArrayList<String>();
   for (int i = 0; i < listEnvelope.size(); i++) {
     sensors.add(searchForSensors_String((Point) listEnvelope.get(i)));
   }
   return sensors;
 }
Exemple #17
0
  @Test
  public void toEnvelope() {
    Coordinate[] coords = getPolyCoords();
    GeometryFactory gf = new GeometryFactory();
    Geometry geom = gf.createPolygon(gf.createLinearRing(coords), null);

    ReferencedEnvelope refEnv = JTS.toEnvelope(geom);
    assertTrue(geom.getEnvelopeInternal().equals(refEnv));
  }
Exemple #18
0
  public static void getAIDMem(List<Geometry> aGeometryList) {

    int numVar = aGeometryList.size();
    //		int[] numRel = new int[8];
    int sum = 0;
    for (int i1 = 0; i1 < numVar; i1++) {
      Geometry a1 = aGeometryList.get(i1);
      Envelope a1m = a1.getEnvelopeInternal();
      //			double[] m1 = new double[4];
      //			m1[0] = a1m.getMinX();
      //			m1[1] = a1m.getMaxX();
      //			m1[2] = a1m.getMinY();
      //			m1[3] = a1m.getMaxY();
      for (int j1 = i1 + 1; j1 < numVar; j1++) {

        Geometry a2 = aGeometryList.get(j1);
        Envelope a2m = a2.getEnvelopeInternal();
        //				double[] m2 = new double[4];
        //				m2[0] = a2m.getMinX();
        //				m2[1] = a2m.getMaxX();
        //				m2[2] = a2m.getMinY();
        //				m2[3] = a2m.getMaxY();
        //				int[] relationAB = new int[8];
        // assume relation table is indexed by i*n+j for each pair (i,j), i<j
        //				relationAB = GeometryRelated.computeRCC8RelationMBR(a1, a2, m1, m2);
        //				if(GeometryRelated.rectangleIntersect(m1, m2)){
        if (a1m.intersects(a2m)) {
          sum += 2;
        }
        //				for(int k=0;k<8;k++){
        //					//we already know relation is basic
        //					if(relationAB[k]==1){
        //						numRel[k]++;
        //						break;
        //					}
        //				}
      }
    }

    System.out.println("Average Intersection Degree: " + ((double) sum / ((double) numVar)));
  }
Exemple #19
0
  @Test
  public void toGeometry_BoundingBox() {
    BoundingBox bbox = new ReferencedEnvelope(-10, 10, -5, 5, null);
    Geometry geom = JTS.toGeometry(bbox);
    assertTrue(geom instanceof com.vividsolutions.jts.geom.Polygon);

    Envelope geomEnv = geom.getEnvelopeInternal();
    assertEquals(-10.0, geomEnv.getMinX(), TOL);
    assertEquals(10.0, geomEnv.getMaxX(), TOL);
    assertEquals(-5.0, geomEnv.getMinY(), TOL);
    assertEquals(5.0, geomEnv.getMaxY(), TOL);
  }
Exemple #20
0
  @Test
  public void toGeometry_Envelope() {
    Envelope refEnv = new Envelope(-10, 10, -5, 5);
    Geometry geom = JTS.toGeometry(refEnv);
    assertTrue(geom instanceof com.vividsolutions.jts.geom.Polygon);

    Envelope geomEnv = geom.getEnvelopeInternal();
    assertEquals(-10.0, geomEnv.getMinX(), TOL);
    assertEquals(10.0, geomEnv.getMaxX(), TOL);
    assertEquals(-5.0, geomEnv.getMinY(), TOL);
    assertEquals(5.0, geomEnv.getMaxY(), TOL);
  }
Exemple #21
0
  @Test
  public void toGeometry_ReferencedEnvelope() {
    ReferencedEnvelope refEnv = new ReferencedEnvelope(-10, 10, -5, 5, DefaultGeographicCRS.WGS84);
    Geometry geom = JTS.toGeometry(refEnv);
    assertTrue(geom instanceof com.vividsolutions.jts.geom.Polygon);

    Envelope geomEnv = geom.getEnvelopeInternal();
    assertEquals(-10.0, geomEnv.getMinX(), TOL);
    assertEquals(10.0, geomEnv.getMaxX(), TOL);
    assertEquals(-5.0, geomEnv.getMinY(), TOL);
    assertEquals(5.0, geomEnv.getMaxY(), TOL);
  }
Exemple #22
0
 /**
  * 根据经度、纬度获取区域编码
  *
  * @param lon 经度
  * @param lat 纬度
  * @return
  * @throws Exception long
  */
 public static long getAreaAnalyzer(double lon, double lat) throws Exception {
   long areacode = -1;
   Geometry geo = new GeometryFactory().createPoint(new Coordinate(lon, lat));
   List<?> areas = areaTree.query(geo.getEnvelopeInternal());
   for (Object obj : areas) {
     AreaNode anode = (AreaNode) obj;
     if (anode.getPolygon().contains(geo)) {
       areacode = anode.getAreaCode();
       break;
     }
   }
   return areacode;
 }
Exemple #23
0
 /**
  * @param geom
  * @param seq
  */
 private boolean decimateOnEnvelope(Geometry geom, LiteCoordinateSequence seq) {
   Envelope env = geom.getEnvelopeInternal();
   if (env.getWidth() <= spanx && env.getHeight() <= spany) {
     double[] coords = seq.getArray();
     int dim = seq.getDimension();
     double[] newcoords = new double[dim * 2];
     for (int i = 0; i < dim; i++) {
       newcoords[i] = coords[i];
       newcoords[dim + i] = coords[coords.length - dim + i];
     }
     seq.setArray(coords);
     return true;
   }
   return false;
 }
  /*
   * (non-Javadoc)
   *
   * @see org.geotools.gce.imagemosaic.jdbc.JDBCAccessBase#getEnvelopeFromResultSet(java.sql.ResultSet)
   */
  @Override
  protected Envelope getEnvelopeFromResultSet(ResultSet r) throws SQLException {
    byte[] bytes = r.getBytes(2);
    WKBReader reader = new WKBReader();
    Geometry bbox = null;

    try {
      bbox = reader.read(bytes);
    } catch (ParseException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      throw new SQLException(e.getMessage());
    }

    return bbox.getEnvelopeInternal();
  }
Exemple #25
0
 /**
  * areaTree全国区域拓扑树初始化
  *
  * @param fileName
  * @throws Exception void
  */
 public static void buildTree(String fileName) throws Exception {
   FileInputStream fis = new FileInputStream(new File(fileName));
   BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
   String line = null;
   AreaNode node = null;
   while ((line = br.readLine()) != null) { // 读取区域文件
     String[] lines = line.split(";");
     Geometry polygon = new WKTReader().read(lines[lines.length - 1]);
     node = new AreaNode(); // 创建节点
     node.setAreaCode(Long.parseLong(lines[0]));
     node.setAreaName(lines[1]);
     node.setPolygon(polygon);
     areaTree.insert(polygon.getEnvelopeInternal(), node); // 向树上添加节点
   }
   fis.close();
   br.close();
   areaTree.build(); // 构建树
 }
Exemple #26
0
 /**
  * Gets the AWT {@link Shape} we'll use to represent {@code geom} on the map.
  *
  * @param geom The geometry we want to draw.
  * @param generalize If true we'll perform generalization
  * @return An AWT Shape instance.
  */
 public Shape getShape(Geometry geom, boolean generalize) {
   if (generalize) {
     Rectangle2DDouble rectangle2dDouble = toPixel(geom.getEnvelopeInternal());
     if ((rectangle2dDouble.getHeight() <= MAXPIXEL_DISPLAY)
         && (rectangle2dDouble.getWidth() <= MAXPIXEL_DISPLAY)) {
       if (geom.getDimension() == 1) {
         Coordinate[] coords = geom.getCoordinates();
         return getShapeWriter()
             .toShape(
                 geom.getFactory()
                     .createLineString(new Coordinate[] {coords[0], coords[coords.length - 1]}));
       } else {
         return rectangle2dDouble;
       }
     }
   }
   return getShapeWriter().toShape(geom);
 }
  Expression clipToWorld(BinarySpatialOperator filter, Expression e) {
    if (e instanceof Literal) {
      Geometry eval = e.evaluate(filter, Geometry.class);
      // Oracle cannot deal with filters using geometries that span beyond the whole world
      // in case the
      if (dialect != null
          && isCurrentGeometryGeodetic()
          && !WORLD.contains(eval.getEnvelopeInternal())) {
        Geometry result = eval.intersection(JTS.toGeometry(WORLD));

        if (result != null && !result.isEmpty()) {
          if (result instanceof GeometryCollection) {
            result = distillSameTypeGeometries((GeometryCollection) result, eval);
          }
          e = new FilterFactoryImpl().createLiteralExpression(result);
        }
      }
    }
    return e;
  }
 /**
  * It retrieves the features falling into the query condition. If the filter is not changed from
  * the previous filter and the layer is not marked to be forcibly refreshed, it does not ask for
  * features from the server, but it returns the former ones
  *
  * @param query The query (geotools) used to filter features
  * @return
  * @throws IOException
  */
 @Override
 public PojoFeatureCollection getFeatures(Query query) throws IOException {
   Filter filter = query.getFilter();
   if (filter == null) {
     throw new UnsupportedOperationException(GisMessage.GENERAL_EXCEPTION_FILTER_NOTFOUND);
   }
   if (!(filter instanceof org.opengis.filter.spatial.BBOX)) {
     throw new UnsupportedOperationException(GisMessage.GENERAL_EXCEPTION_TYPE_NOTSUPPORTED);
   }
   org.opengis.filter.spatial.BBOX bboxFilter = (org.opengis.filter.spatial.BBOX) filter;
   org.geotools.filter.LiteralExpressionImpl literalExpression =
       (org.geotools.filter.LiteralExpressionImpl) bboxFilter.getExpression2();
   Geometry filteringGeometry = (Geometry) literalExpression.getValue();
   Envelope boundingBox = (Envelope) filteringGeometry.getEnvelopeInternal();
   double west = boundingBox.getMinX();
   double east = boundingBox.getMaxX();
   double south = boundingBox.getMinY();
   double north = boundingBox.getMaxY();
   this.ModifyFeatureCollection(west, south, east, north);
   return this.collection;
 }
  public void runAlgorithm() throws IOException {

    /*
     * get tracks
     */
    Envelope env = bbox.getEnvelopeInternal();
    List<String> trackIDs = getTrackIDs(env.getMinX(), env.getMinY(), env.getMaxX(), env.getMaxY());

    /*
     * foreach track
     *
     */

    for (String trackID : trackIDs) {

      runAlgorithm(trackID);
      /*
       * continue with next track
       */
    }
  }
  /**
   * This method computes reprojected bounds the hard way, but computing them feature by feature.
   * This method could be faster if computed the reprojected bounds by reprojecting the original
   * feature bounds a Shape object, thus getting the true shape of the reprojected envelope, and
   * then computing the minimum and maximum coordinates of that new shape. The result would not a
   * true representation of the new bounds.
   *
   * @see org.geotools.data.FeatureResults#getBounds()
   */
  public ReferencedEnvelope getBounds() {
    FeatureIterator<SimpleFeature> r = features();
    try {
      Envelope newBBox = new Envelope();
      Envelope internal;
      SimpleFeature feature;

      while (r.hasNext()) {
        feature = r.next();
        final Geometry geom = ((Geometry) feature.getDefaultGeometry());
        if (geom != null) {
          internal = geom.getEnvelopeInternal();
          newBBox.expandToInclude(internal);
        }
      }
      return ReferencedEnvelope.reference(newBBox);
    } catch (Exception e) {
      throw new RuntimeException("Exception occurred while computing reprojected bounds", e);
    } finally {
      r.close();
    }
  }