Example #1
0
  /**
   * Find the innermost enclosing shell EdgeRing containing the argument EdgeRing, if any. The
   * innermost enclosing ring is the <i>smallest</i> enclosing ring. The algorithm used depends on
   * the fact that: <br>
   * ring A contains ring B iff envelope(ring A) contains envelope(ring B) <br>
   * This routine is only safe to use if the chosen point of the hole is known to be properly
   * contained in a shell (which is guaranteed to be the case if the hole does not touch its shell)
   *
   * @return containing EdgeRing, if there is one or null if no containing EdgeRing is found
   */
  public static EdgeRing findEdgeRingContaining(EdgeRing testEr, List shellList) {
    LinearRing testRing = testEr.getRing();
    Envelope testEnv = testRing.getEnvelopeInternal();
    Coordinate testPt = testRing.getCoordinateN(0);

    EdgeRing minShell = null;
    Envelope minShellEnv = null;
    for (Iterator it = shellList.iterator(); it.hasNext(); ) {
      EdgeRing tryShell = (EdgeRing) it.next();
      LinearRing tryShellRing = tryShell.getRing();
      Envelope tryShellEnv = tryShellRing.getEnvelopeInternal();
      // the hole envelope cannot equal the shell envelope
      // (also guards against testing rings against themselves)
      if (tryShellEnv.equals(testEnv)) continue;
      // hole must be contained in shell
      if (!tryShellEnv.contains(testEnv)) continue;

      testPt =
          CoordinateArrays.ptNotInList(testRing.getCoordinates(), tryShellRing.getCoordinates());
      boolean isContained = false;
      if (CGAlgorithms.isPointInRing(testPt, tryShellRing.getCoordinates())) isContained = true;

      // check if this new containing ring is smaller than the current minimum ring
      if (isContained) {
        if (minShell == null || minShellEnv.contains(tryShellEnv)) {
          minShell = tryShell;
          minShellEnv = minShell.getRing().getEnvelopeInternal();
        }
      }
    }
    return minShell;
  }
Example #2
0
  /** {@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;
  }
  /*
   * Adds a feature layer to the geopackage.
   */
  void addFeatureLayer(
      GeoPackage geopkg, FeatureLayer layer, MapLayerInfo mapLayer, WMSMapContent map)
      throws IOException {

    FeatureEntry e = new FeatureEntry();
    initEntry(e, layer, mapLayer, map);

    Filter filter = layer.getQuery().getFilter();
    GeometryDescriptor gd = mapLayer.getFeature().getFeatureType().getGeometryDescriptor();
    if (gd != null) {
      Envelope bnds = bounds(map);
      BBOX bboxFilter =
          filterFactory.bbox(
              gd.getLocalName(),
              bnds.getMinX(),
              bnds.getMinY(),
              bnds.getMaxX(),
              bnds.getMaxY(),
              map.getRequest().getSRS());
      filter = filterFactory.and(filter, bboxFilter);
    }

    LOGGER.fine("Creating feature entry" + e.getTableName());
    geopkg.add(e, layer.getSimpleFeatureSource(), filter);
  }
 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;
 }
  public static double diagonalSize(Envelope env) {
    if (env.isNull()) return 0.0;

    double width = env.getWidth();
    double hgt = env.getHeight();
    return Math.sqrt(width * width + hgt * hgt);
  }
 private EXGeographicBoundingBox getGeographicBoundingBox(Envelope env, String epsgCode) {
   Envelope newEnvelope;
   if ("EPSG:4326".equals(epsgCode)) {
     newEnvelope = env;
   } else {
     try {
       GeometryFactory gf = new GeometryFactory();
       Polygon poly = (Polygon) gf.toGeometry(env);
       ST_Transform transformFunction = new ST_Transform();
       CoordinateReferenceSystem inputCRS = DataSourceFactory.getCRSFactory().getCRS(epsgCode);
       Value val =
           transformFunction.evaluate(
               null,
               ValueFactory.createValue(poly, inputCRS),
               ValueFactory.createValue("EPSG:4326"));
       newEnvelope = val.getAsGeometry().getEnvelopeInternal();
     } catch (FunctionException fe) {
       return getDummyGeographic();
     } catch (CRSException ex) {
       return getDummyGeographic();
     }
   }
   EXGeographicBoundingBox ret = new EXGeographicBoundingBox();
   ret.setEastBoundLongitude(newEnvelope.getMaxX());
   ret.setWestBoundLongitude(newEnvelope.getMinX());
   ret.setNorthBoundLatitude(newEnvelope.getMaxY());
   ret.setSouthBoundLatitude(newEnvelope.getMinY());
   return ret;
 }
 /**
  * Ajusta el tamaño de la ventana al envelope pasado como parámetro
  *
  * @param ctx
  * @param newWrapperEnvelope
  * @param viewport
  */
 public static void resizeViewToEnvelope(
     PlugInContext ctx, Envelope newWrapperEnvelope, IViewport viewport) {
   // ajustamos las proporciones de la ventana a las de la feature
   JInternalFrame activeInternalFrame = ctx.getActiveInternalFrame();
   Dimension dimView = ((Dimension) ctx.getLayerViewPanel()).getSize();
   Double widthView = dimView.getWidth();
   Double heightView = dimView.getHeight();
   int widthDiff = (int) (activeInternalFrame.getWidth() - widthView);
   int heightDiff = (int) (activeInternalFrame.getHeight() - heightView);
   Integer newWidth =
       (int)
           ((newWrapperEnvelope.getWidth() / viewport.getEnvelopeInModelCoordinates().getWidth())
               * widthView);
   Integer newHeight =
       (int)
           ((newWrapperEnvelope.getHeight() / viewport.getEnvelopeInModelCoordinates().getHeight())
               * heightView);
   Dimension newDimensionView = new Dimension(newWidth + widthDiff, newHeight + heightDiff);
   activeInternalFrame.setSize(newDimensionView);
   // zoom al envelope actual
   try {
     viewport.zoom(newWrapperEnvelope);
   } catch (NoninvertibleTransformException e) {
     log.warn("No se ha podido alcanzar el zoom " + newWrapperEnvelope);
   }
 }
Example #8
0
 /**
  * Gets the scale denominator. If the scale is 1:1000 this method returns 1000. The scale is not
  * absolutely precise and errors of 2% have been measured.
  *
  * @return
  */
 public double getScaleDenominator() {
   if (adjustedExtent.isNull()) {
     return 0;
   } else {
     return adjustedExtent.getWidth() / getImageMeters();
   }
 }
 /**
  * Test that point features are rendered at the expected image coordinates when the map is
  * rotated. StreamingRenderer
  *
  * @throws Exception
  */
 @Test
 public void testRotatedTransform() throws Exception {
   // If we rotate the world rectangle + 90 degrees around (0,0), we get the screen rectangle
   final Rectangle screen = new Rectangle(0, 0, 100, 50);
   final Envelope world = new Envelope(0, 50, 0, -100);
   final AffineTransform worldToScreen =
       AffineTransform.getRotateInstance(Math.toRadians(90), 0, 0);
   DefaultFeatureCollection fc = new DefaultFeatureCollection();
   fc.add(createPoint(0, 0));
   fc.add(createPoint(world.getMaxX(), world.getMinY()));
   MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
   mapContext.addLayer((FeatureCollection) fc, createPointStyle());
   BufferedImage image =
       new BufferedImage(screen.width, screen.height, BufferedImage.TYPE_4BYTE_ABGR);
   final StreamingRenderer sr = new StreamingRenderer();
   sr.setContext(mapContext);
   sr.paint(image.createGraphics(), screen, worldToScreen);
   assertTrue("Pixel should be drawn at 0,0 ", image.getRGB(0, 0) != 0);
   assertTrue(
       "Pixel should not be drawn in image centre ",
       image.getRGB(screen.width / 2, screen.height / 2) == 0);
   assertTrue(
       "Pixel should be drawn at image max corner ",
       image.getRGB(screen.width - 1, screen.height - 1) != 0);
 }
  public Iterable<Tuple2<Integer, Point>> call(Iterator<Point> s) throws Exception {
    // int id=-1;
    ArrayList<Tuple2<Integer, Point>> list = new ArrayList<Tuple2<Integer, Point>>();

    while (s.hasNext()) {
      Point currentElement = s.next();
      Integer id = 0;
      for (int j = 0; j < gridNumberVertical; j++) {
        for (int i = 0; i < gridNumberHorizontal; i++) {
          Envelope currentGrid =
              new Envelope(
                  gridHorizontalBorder[i],
                  gridHorizontalBorder[i + 1],
                  gridVerticalBorder[j],
                  gridVerticalBorder[j + 1]);
          /*if(currentElement.getX()>=gridHorizontalBorder[i] && currentElement.getX()<=gridHorizontalBorder[i+1] && currentElement.getY()>=gridVerticalBorder[j] && currentElement.getY()<=gridVerticalBorder[j+1])
          {
          	id=i*gridNumberHorizontal+j;
          	list.add(new Tuple2(id,currentElement));
          }*/
          if (currentGrid.intersects(currentElement.getCoordinate())
              || currentGrid.contains(currentElement.getCoordinate())) {
            // id=j*gridNumberHorizontal+i;
            list.add(new Tuple2(id, currentElement));
          }
          id++;
        }
      }
    }

    return list;
  }
 public void zoomToVertex(Vertex v) {
   Envelope e = new Envelope();
   e.expandToInclude(v.getCoordinate());
   e.expandBy(0.002);
   modelBounds = e;
   drawLevel = DRAW_ALL;
 }
  public void drawAnotation(GraphBuilderAnnotation anno) {
    Envelope env = new Envelope();

    Edge e = anno.getReferencedEdge();
    if (e != null) {
      this.enqueueHighlightedEdge(e);
      env.expandToInclude(e.getFromVertex().getCoordinate());
      env.expandToInclude(e.getToVertex().getCoordinate());
    }

    ArrayList<Vertex> vertices = new ArrayList<Vertex>();
    Vertex v = anno.getReferencedVertex();
    if (v != null) {
      env.expandToInclude(v.getCoordinate());
      vertices.add(v);
    }

    if (e == null && v == null) return;

    // make it a little bigger, especially needed for STOP_UNLINKED
    env.expandBy(0.02);

    // highlight relevant things
    this.clearHighlights();
    this.setHighlightedVertices(vertices);

    // zoom the graph display
    this.zoomToEnvelope(env);

    // and draw
    this.draw();
  }
  /**
   * Creates a elliptical arc, as a LineString.
   *
   * @return an elliptical arc
   */
  public LineString createArc(double startAng, double endAng) {
    Envelope env = dim.getEnvelope();
    double xRadius = env.getWidth() / 2.0;
    double yRadius = env.getHeight() / 2.0;

    double centreX = env.getMinX() + xRadius;
    double centreY = env.getMinY() + yRadius;

    double angSize = (endAng - startAng);
    if (angSize <= 0.0 || angSize > 2 * Math.PI) angSize = 2 * Math.PI;
    double angInc = angSize / nPts;

    Coordinate[] pts = new Coordinate[nPts];
    int iPt = 0;
    for (int i = 0; i < nPts; i++) {
      double ang = startAng + i * angInc;
      double x = xRadius * Math.cos(ang) + centreX;
      double y = yRadius * Math.sin(ang) + centreY;
      Coordinate pt = new Coordinate(x, y);
      geomFact.getPrecisionModel().makePrecise(pt);
      pts[iPt++] = pt;
    }
    LineString line = geomFact.createLineString(pts);
    return line;
  }
Example #14
0
 public Node(Envelope env, int level) {
   // this.parent = parent;
   this.env = env;
   this.level = level;
   centrex = (env.getMinX() + env.getMaxX()) / 2;
   centrey = (env.getMinY() + env.getMaxY()) / 2;
 }
Example #15
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();
  }
Example #16
0
 /** Compute the parameters need to create each cells */
 private void initParameters() {
   this.minX = envelope.getMinX();
   this.minY = envelope.getMinY();
   double cellWidth = envelope.getWidth();
   double cellHeight = envelope.getHeight();
   this.maxI = (int) Math.ceil(cellWidth / deltaX);
   this.maxJ = (int) Math.ceil(cellHeight / deltaY);
 }
 void matchAspect() {
   /* Basic sinusoidal projection of lat/lon data to square pixels */
   double yCenter = modelBounds.centre().y;
   float xScale = cos(radians((float) yCenter));
   double newX =
       modelBounds.getHeight() * (1 / xScale) * ((float) this.getWidth() / this.getHeight());
   modelBounds.expandBy((newX - modelBounds.getWidth()) / 2f, 0);
 }
 public void zoomToLocation(Coordinate c) {
   Envelope e = new Envelope();
   e.expandToInclude(c);
   e.expandBy(0.002);
   modelBounds = e;
   matchAspect();
   drawLevel = DRAW_ALL;
 }
Example #19
0
 @Test
 public void testBounds() throws Exception {
   Envelope bounds = ws.get("states").bounds();
   assertEquals(-124.73, bounds.getMinX(), 0.01);
   assertEquals(24.96, bounds.getMinY(), 0.01);
   assertEquals(-66.97, bounds.getMaxX(), 0.01);
   assertEquals(49.37, bounds.getMaxY(), 0.01);
 }
Example #20
0
  public static Node createExpanded(Node node, Envelope addEnv) {
    Envelope expandEnv = new Envelope(addEnv);
    if (node != null) expandEnv.expandToInclude(node.env);

    Node largerNode = createNode(expandEnv);
    if (node != null) largerNode.insertNode(node);
    return largerNode;
  }
Example #21
0
 public void testProducedRasterEnvelope() throws Exception {
   DataSource ds = dsf.getDataSource("raster");
   ds.open();
   SpatialDataSourceDecorator sds = new SpatialDataSourceDecorator(ds);
   Envelope env = sds.getFullExtent();
   assertTrue(env.getWidth() > 0);
   assertTrue(env.getHeight() > 0);
   ds.close();
 }
  public Element encode(Object object, Document document, Element value) throws Exception {
    Envelope envelope = (Envelope) object;

    if (envelope.isNull()) {
      value.appendChild(document.createElementNS(GML.NAMESPACE, GML.Null.getLocalPart()));
    }

    return null;
  }
Example #23
0
 /**
  * Creates the Envelope for all passed sampling features.
  *
  * @param samplingFeatures the sampling features
  * @return the envelope for all features
  */
 protected Envelope createEnvelopeFrom(List<SamplingFeature> samplingFeatures) {
   Envelope featureEnvelope = new Envelope();
   for (SamplingFeature samplingFeature : samplingFeatures) {
     if (samplingFeature.isSetGeometry()) {
       featureEnvelope.expandToInclude(samplingFeature.getGeometry().getEnvelopeInternal());
     }
   }
   return featureEnvelope;
 }
  /**
   * 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;
  }
    @Override
    public ReferencedEnvelope getBounds() {
      if (bounds == null) {
        Envelope e = new Envelope();
        e.setToNull();

        bounds = new ReferencedEnvelope(e, DefaultGeographicCRS.WGS84);
      }
      return bounds;
    }
  protected Shape getShape() {
    if (zoomBoxEnd == null) return null;

    Envelope envModel = getEnvelope();

    Point2D base = toView(new Coordinate(envModel.getMinX(), envModel.getMaxY()));
    double width = toView(envModel.getWidth());
    double height = toView(envModel.getHeight());
    return new Rectangle2D.Double(base.getX(), base.getY(), width, height);
  }
Example #27
0
  /**
   * @param li ImageLevelInfo object
   * @param con JDBC Connection
   * @return the resolution for li, based on a random chosen tile
   * @throws SQLException
   * @throws IOException
   */
  protected double[] getPixelResolution(ImageLevelInfo li, Connection con)
      throws SQLException, IOException {
    double[] result = null;
    String statementString = getRandomTileStatement(li);
    PreparedStatement s = con.prepareStatement(statementString);
    ResultSet r = s.executeQuery();

    while (r.next()) {
      byte[] tileBytes = getTileBytes(r);

      if (tileBytes == null) {
        continue;
      }

      BufferedImage buffImage = null;
      li.setCanImageIOReadFromInputStream(true);
      try {
        buffImage = ImageIO.read(new ByteArrayInputStream(tileBytes));
      } catch (IOException e) {
      }

      if (buffImage == null) {
        if (LOGGER.isLoggable(Level.WARNING)) {
          LOGGER.warning(
              "Image IO cannot read from ByteInputStream,use less efficient jai methods");
        }
        li.setCanImageIOReadFromInputStream(false);
        SeekableStream stream = new ByteArraySeekableStream(tileBytes);
        String decoderName = null;

        for (String dn : ImageCodec.getDecoderNames(stream)) {
          decoderName = dn;
          break;
        }

        ImageDecoder decoder = ImageCodec.createImageDecoder(decoderName, stream, null);
        PlanarImage img = PlanarImage.wrapRenderedImage(decoder.decodeAsRenderedImage());
        buffImage = img.getAsBufferedImage();
      }

      Envelope env = getEnvelopeFromResultSet(r);

      result =
          new double[] {
            env.getWidth() / buffImage.getWidth(), env.getHeight() / buffImage.getHeight()
          };

      break;
    }

    r.close();
    s.close();

    return result;
  }
Example #28
0
  /**
   * @param envelope
   * @param width
   * @param height
   * @return
   * @throws ThinklabResourceNotFoundException
   */
  private BufferedImage getWMSImage(Envelope envelope, int width, int height)
      throws ThinklabResourceNotFoundException {

    BufferedImage ret = null;
    initializeWms();

    String sig = envelope.toString() + "," + width + "," + height;

    if (_cache.containsKey(sig)) return ImageUtil.clone(_cache.get(sig));

    if (_wms != null) {

      GetMapRequest request = _wms.createGetMapRequest();
      request.setFormat("image/png");
      request.setDimensions("" + width, "" + height);
      request.setTransparent(true);

      // FIXME this assumes the envelope is in lat/lon
      request.setSRS("EPSG:4326");

      String bbox =
          (float) envelope.getMinX()
              + ","
              + (float) envelope.getMinY()
              + ","
              + (float) envelope.getMaxX()
              + ","
              + (float) envelope.getMaxY();

      request.setBBox(bbox);

      for (Layer layer : getWMSLayers()) {
        request.addLayer(layer);
      }

      GetMapResponse response = null;
      try {

        System.out.println(request.getFinalURL());

        response = (GetMapResponse) _wms.issueRequest(request);
        ret = ImageIO.read(response.getInputStream());
      } catch (Exception e) {
        Geospace.get().logger().warn("cannot get WFS imagery: " + e.getLocalizedMessage());
        return null;
      }

      /*
       * FIXME this obviously must have a limit
       */
      if (ret != null) _cache.put(sig, ImageUtil.clone(ret));
    }

    return ret;
  }
Example #29
0
  /**
   * Step 2 of the bootstrapping process.
   *
   * <p>Calculating the the extent for each image level (original + pyramids). This calculation is
   * only done if the extent info in the master table is SQL NULL. After calculation the meta table
   * is updated with the result to avoid this operation in the future.
   *
   * @param coverageName The coverage name in the sql meta table
   * @param con JDBC connection
   * @throws SQLException
   * @throws IOException
   */
  void calculateExtentsFromDB(String coverageName, Connection con)
      throws SQLException, IOException {
    PreparedStatement stmt = con.prepareStatement(config.getSqlUpdateMosaicStatement());

    List<ImageLevelInfo> toBeRemoved = new ArrayList<ImageLevelInfo>();

    for (ImageLevelInfo li : levelInfos) {
      if (li.getCoverageName().equals(coverageName) == false) {
        continue;
      }

      if (li.calculateExtentsNeeded() == false) {
        continue;
      }

      Date start = new Date();
      if (LOGGER.isLoggable(Level.INFO)) LOGGER.info("Calculate extent for " + li.toString());

      Envelope env = getExtent(li, con);

      if (env == null) {
        if (LOGGER.isLoggable(Level.WARNING))
          LOGGER.log(Level.WARNING, "No extent, removing this level");
        toBeRemoved.add(li);

        continue;
      }

      li.setExtentMaxX(new Double(env.getMaxX()));
      li.setExtentMaxY(new Double(env.getMaxY()));
      li.setExtentMinX(new Double(env.getMinX()));
      li.setExtentMinY(new Double(env.getMinY()));

      stmt.setDouble(1, li.getExtentMaxX().doubleValue());
      stmt.setDouble(2, li.getExtentMaxY().doubleValue());
      stmt.setDouble(3, li.getExtentMinX().doubleValue());
      stmt.setDouble(4, li.getExtentMinY().doubleValue());
      stmt.setString(5, li.getCoverageName());
      stmt.setString(6, li.getTileTableName());
      stmt.setString(7, li.getSpatialTableName());
      stmt.execute();

      long msecs = (new Date()).getTime() - start.getTime();

      if (LOGGER.isLoggable(Level.INFO))
        LOGGER.info("Calculate extent for " + li.toString() + " finished in " + msecs + " ms ");
    }

    levelInfos.removeAll(toBeRemoved);

    if (stmt != null) {
      stmt.close();
    }
  }
Example #30
0
  public boolean onToolTouchEvent(MotionEvent event) {
    if (mapView == null || mapView.isClickable()) {
      return false;
    }
    Projection pj = editingViewProjection;

    // handle drawing
    currentX = event.getX();
    currentY = event.getY();

    int action = event.getAction();
    switch (action) {
      case MotionEvent.ACTION_DOWN:
        startGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        pj.toPixels(startGeoPoint, startP);
        endP.set(startP.x, startP.y);

        drawingPath.reset();
        drawingPath.moveTo(startP.x, startP.y);

        lastX = currentX;
        lastY = currentY;
        break;
      case MotionEvent.ACTION_MOVE:
        float dx = currentX - lastX;
        float dy = currentY - lastY;
        if (abs(dx) < 1 && abs(dy) < 1) {
          lastX = currentX;
          lastY = currentY;
          return true;
        }
        GeoPoint currentGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        pj.toPixels(currentGeoPoint, tmpP);
        drawingPath.lineTo(tmpP.x, tmpP.y);
        endP.set(tmpP.x, tmpP.y);

        EditManager.INSTANCE.invalidateEditingView();
        break;
      case MotionEvent.ACTION_UP:
        GeoPoint endGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        GeometryFactory gf = new GeometryFactory();
        Coordinate startCoord =
            new Coordinate(startGeoPoint.getLongitude(), startGeoPoint.getLatitude());
        com.vividsolutions.jts.geom.Point startPoint = gf.createPoint(startCoord);
        Coordinate endCoord = new Coordinate(endGeoPoint.getLongitude(), endGeoPoint.getLatitude());
        com.vividsolutions.jts.geom.Point endPoint = gf.createPoint(endCoord);
        Envelope env = new Envelope(startCoord, endCoord);
        select(env.getMaxY(), env.getMinX(), env.getMinY(), env.getMaxX(), startPoint, endPoint);
        //            EditManager.INSTANCE.invalidateEditingView();
        break;
    }

    return true;
  }