private void addEnv(@Nullable Bounded node) {
   if (node == null) {
     return;
   }
   Envelope env = envBuff;
   env.setToNull();
   node.expand(env);
   if (env.isNull()) {
     return;
   }
   if (isPoint(env)) {
     points.add(env.getMinX(), env.getMinY());
   } else if (isOrthoLine(env)) {
     // handle the case where the envelope is given by an orthogonal line so we don't add a
     // zero area polygon
     double width = env.getWidth();
     GrowableCoordinateSequence cs = new GrowableCoordinateSequence();
     if (width == 0D) {
       cs.add(env.getMinX(), env.getMinY());
       cs.add(env.getMinX(), env.getMaxY());
     } else {
       cs.add(env.getMinX(), env.getMinY());
       cs.add(env.getMaxX(), env.getMinY());
     }
     nonPoints.add(GEOM_FACTORY.createLineString(cs));
   } else {
     nonPoints.add(JTS.toGeometry(env, GEOM_FACTORY));
   }
 }
Пример #2
0
  /**
   * Getes the coordinates for the rectangle starting with the lower left point. The coordinates are
   * oriented CW.
   *
   * @return the coordinates for the rectangle
   */
  protected List getCoordinatesOfEnvelope() {
    Envelope env = getEnvelope();

    List coords = new ArrayList();
    coords.add(new Coordinate(env.getMinX(), env.getMinY()));
    coords.add(new Coordinate(env.getMinX(), env.getMaxY()));
    coords.add(new Coordinate(env.getMaxX(), env.getMaxY()));
    coords.add(new Coordinate(env.getMaxX(), env.getMinY()));
    coords.add(new Coordinate(env.getMinX(), env.getMinY()));
    return coords;
  }
Пример #3
0
  /**
   * API Method: getURL
   *
   * @return url create the url of a tile based on bounds
   */
  @Override
  public String getUrl(Envelope bounds) {
    bounds = this.adjustBoundsByGutter(bounds);
    // Util.printDebugMessage("@...AgsTiled.getUrl() is called here with bounds:" + bounds.toBBOX()
    // + "...");
    double res = this.map.getResolution();
    String path = null;
    String url = null;

    if (this.tileFullExtent.intersects(bounds) == true) {
      int col;
      if (this.tileOrigin.x <= bounds.getMinX()) {
        col =
            (int)
                Math.round(
                    (bounds.getMinX() - this.tileOrigin.x) / (res * this.tileSize.getWidth()));
      } else if (this.tileOrigin.x >= bounds.getMaxX()) {
        col =
            (int)
                Math.round(
                    (this.tileOrigin.x - bounds.getMaxX()) / (res * this.tileSize.getWidth()));
      } else {
        Util.printErrorMessage("...invalid tileOrigin...");
        return getTransparentTileUrl();
      }
      int row;
      if (this.tileOrigin.y >= bounds.getMaxY()) {
        row =
            (int)
                Math.round(
                    (this.tileOrigin.y - bounds.getMaxY()) / (res * this.tileSize.getHeight()));
      } else if (this.tileOrigin.y <= bounds.getMinY()) {
        row =
            (int)
                Math.round(
                    (bounds.getMinY() - this.tileOrigin.y) / (res * this.tileSize.getHeight()));
      } else {
        // Util.printDebugMessage("...invalid tileOrigin...");
        return getTransparentTileUrl();
      }
      int zoom = this.map.getZoom();
      if (this.mimeType.equalsIgnoreCase("") == true) {
        path = zoom + "/" + row + "/" + col;
      } else {
        path = zoom + "/" + row + "/" + col + "." + this.mimeType;
      }
      url = this.url;

      return url + path;
    } else {
      // area outside of tiles' full extent
      return getTransparentTileUrl();
    }
  }
Пример #4
0
  /** @throws RuntimeException */
  private void calculateAffineTransform() {
    if (extent == null) {
      return;
    } else if (image == null || getWidth() == 0 || getHeight() == 0) {
      return;
    }

    if (adjustExtent) {
      double escalaX = getWidth() / extent.getWidth();
      double escalaY = getHeight() / extent.getHeight();

      double xCenter = extent.getMinX() + extent.getWidth() / 2.0;
      double yCenter = extent.getMinY() + extent.getHeight() / 2.0;
      adjustedExtent = new Envelope();

      double scale;
      if (escalaX < escalaY) {
        scale = escalaX;
        double newHeight = getHeight() / scale;
        double newX = xCenter - (extent.getWidth() / 2.0);
        double newY = yCenter - (newHeight / 2.0);
        adjustedExtent = new Envelope(newX, newX + extent.getWidth(), newY, newY + newHeight);
      } else {
        scale = escalaY;
        double newWidth = getWidth() / scale;
        double newX = xCenter - (newWidth / 2.0);
        double newY = yCenter - (extent.getHeight() / 2.0);
        adjustedExtent = new Envelope(newX, newX + newWidth, newY, newY + extent.getHeight());
      }

      trans.setToIdentity();
      trans.concatenate(AffineTransform.getScaleInstance(scale, -scale));
      trans.concatenate(
          AffineTransform.getTranslateInstance(
              -adjustedExtent.getMinX(), -adjustedExtent.getMinY() - adjustedExtent.getHeight()));
    } else {
      adjustedExtent = new Envelope(extent);
      trans.setToIdentity();
      double scaleX = getWidth() / extent.getWidth();
      double scaleY = getHeight() / extent.getHeight();

      /** Map Y axis grows downward but CRS grows upward => -1 */
      trans.concatenate(AffineTransform.getScaleInstance(scaleX, -scaleY));
      trans.concatenate(
          AffineTransform.getTranslateInstance(
              -extent.getMinX(), -extent.getMinY() - extent.getHeight()));
    }
    try {
      transInv = trans.createInverse();
    } catch (NoninvertibleTransformException ex) {
      transInv = null;
      throw new RuntimeException(ex);
    }
  }
Пример #5
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)));
  }
Пример #6
0
  /*
   * 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);
  }
Пример #7
0
  public void testCropRectangle() throws Exception {
    final Envelope rasterEnvelope = geoRasterSrc.getMetadata().getEnvelope();
    geoRasterSrc.save(tmpData + "1.tif");
    final int buffer = (int) (rasterEnvelope.getWidth() / 2.3);
    final Rectangle2D cropRectangle =
        new Rectangle2D.Double(
            rasterEnvelope.getMinX() + buffer,
            rasterEnvelope.getMinY() + buffer,
            rasterEnvelope.getWidth() - 2 * buffer,
            rasterEnvelope.getHeight() - 2 * buffer);
    geoRasterDst = geoRasterSrc.doOperation(new Crop(cropRectangle));
    geoRasterDst.save(tmpData + "2.tif");

    assertTrue(geoRasterDst.getWidth() > 0);
    assertTrue(geoRasterDst.getHeight() > 0);

    final ImagePlus srcImagePlus = geoRasterSrc.getImagePlus();
    final ImagePlus dstImagePlus = geoRasterDst.getImagePlus();
    RasterMetadata dstMetadata = geoRasterDst.getMetadata();
    RasterMetadata srcMetadata = geoRasterSrc.getMetadata();
    assertTrue(dstMetadata.getEnvelope().getMinX() < cropRectangle.getMinX());
    assertTrue(dstMetadata.getEnvelope().getMinY() < cropRectangle.getMinY());
    assertTrue(dstMetadata.getEnvelope().getMaxX() > cropRectangle.getMaxX());
    assertTrue(dstMetadata.getEnvelope().getMaxY() > cropRectangle.getMaxY());
    assertTrue(dstMetadata.getEnvelope().getWidth() < srcMetadata.getEnvelope().getWidth());
    checkCrop(geoRasterDst.getMetadata().getEnvelope(), srcImagePlus, dstImagePlus);
  }
Пример #8
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;
 }
 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;
 }
Пример #10
0
  /**
   * Utility method to create a ReferencedEnvelope from an JTS Envelope class, supporting 2d as well
   * as 3d envelopes (returning the right class).
   *
   * @param env The JTS Envelope object
   * @return ReferencedEnvelope, ReferencedEnvelope3D if it is 3d,<br>
   *     results in a null/an empty envelope, if input envelope was a null/an empty envelope
   */
  public static ReferencedEnvelope create(Envelope env, CoordinateReferenceSystem crs) {
    if (env == null) {
      return null;
    }
    if (crs.getCoordinateSystem().getDimension() >= 3) {
      if (env.isNull()) {
        return new ReferencedEnvelope3D(crs);
      } else {
        return new ReferencedEnvelope3D(
            env.getMinX(),
            env.getMaxX(),
            env.getMinY(),
            env.getMaxY(),
            Double.NaN,
            Double.NaN,
            crs);
      }
    }

    if (env.isNull()) {
      return new ReferencedEnvelope(crs);
    } else {
      return new ReferencedEnvelope(env, crs);
    }
  }
Пример #11
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();
  }
Пример #12
0
  private void renderGridCoverage(
      Graphics2D graphics,
      Envelope bounds,
      Dimension dimension,
      ReferencedEnvelope requestBBox,
      BufferedImage image)
      throws Exception {
    CoordinateReferenceSystem destinationCRS = getContext().getCRS();

    Envelope envelope = bounds;
    if (envelope == null || envelope.isNull()) {
      // get the bounds from the context
      envelope = getContext().getImageBounds();
    }
    Point upperLeft =
        getContext().worldToPixel(new Coordinate(envelope.getMinX(), envelope.getMinY()));
    Point bottomRight =
        getContext().worldToPixel(new Coordinate(envelope.getMaxX(), envelope.getMaxY()));
    Rectangle screenSize = new Rectangle(upperLeft);
    screenSize.add(bottomRight);

    GridCoverage2D coverage = convertImageToGridCoverage(requestBBox, image);

    AffineTransform worldToScreen =
        RendererUtilities.worldToScreenTransform(envelope, screenSize, destinationCRS);
    GridCoverageRenderer paint =
        new GridCoverageRenderer(destinationCRS, envelope, screenSize, worldToScreen);

    RasterSymbolizer symbolizer =
        CommonFactoryFinder.getStyleFactory(null).createRasterSymbolizer();

    paint.paint(graphics, coverage, symbolizer);
  }
Пример #13
0
 /**
  * Turns an envelope into an array [minX,minY,maxX,maxY]
  *
  * @param env envelope representing bounding box
  * @return this
  */
 protected JSONBuilder writeBoundingBox(Envelope env) {
   this.key("bbox");
   this.array();
   if (axisOrder == CRS.AxisOrder.NORTH_EAST) {
     roundedValue(env.getMinY());
     roundedValue(env.getMinX());
     roundedValue(env.getMaxY());
     roundedValue(env.getMaxX());
   } else {
     roundedValue(env.getMinX());
     roundedValue(env.getMinY());
     roundedValue(env.getMaxX());
     roundedValue(env.getMaxY());
   }
   return this.endArray();
 }
  /**
   * 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;
  }
Пример #15
0
 /**
  * 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);
 }
Пример #16
0
  /**
   * Returns a two element array of PropertyName, Literal ( Geometry )
   *
   * @param node The parse tree.
   * @return A two element array of expressions for a BinarySpatialOp type.
   */
  static Expression[] spatial(Node node, FilterFactory2 ff, GeometryFactory gf) {
    PropertyName name = (PropertyName) node.getChildValue(PropertyName.class);
    Expression spatial = null;

    if (node.hasChild(Geometry.class)) {
      spatial = ff.literal(node.getChildValue(Geometry.class));
    } else if (node.hasChild(Envelope.class)) {
      // JD: creating an envelope here would break a lot of our code, for instance alot of
      // code that encodes a filter into sql will choke on this
      Envelope envelope = (Envelope) node.getChildValue(Envelope.class);
      Polygon polygon =
          gf.createPolygon(
              gf.createLinearRing(
                  new Coordinate[] {
                    new Coordinate(envelope.getMinX(), envelope.getMinY()),
                    new Coordinate(envelope.getMaxX(), envelope.getMinY()),
                    new Coordinate(envelope.getMaxX(), envelope.getMaxY()),
                    new Coordinate(envelope.getMinX(), envelope.getMaxY()),
                    new Coordinate(envelope.getMinX(), envelope.getMinY())
                  }),
              null);

      if (envelope instanceof ReferencedEnvelope) {
        polygon.setUserData(((ReferencedEnvelope) envelope).getCoordinateReferenceSystem());
      }

      spatial = ff.literal(polygon);
    } else {
      // look for an expression that is not a property name
      for (Iterator c = node.getChildren().iterator(); c.hasNext(); ) {
        Node child = (Node) c.next();

        // if property name, skip
        if (child.getValue() instanceof PropertyName) {
          continue;
        }

        // if expression, use it
        if (child.getValue() instanceof Expression) {
          spatial = (Expression) child.getValue();
          break;
        }
      }
    }

    return new Expression[] {name, spatial};
  }
Пример #17
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);
 }
Пример #18
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);
 }
Пример #19
0
 private Envelope getMetaTileEnvelope(
     GetMapRequest request, Point tileCoords, Point metaTileCoords) {
   Envelope bbox = request.getBbox();
   double minx = bbox.getMinX() + (metaTileCoords.x - tileCoords.x) * bbox.getWidth();
   double miny = bbox.getMinY() + (metaTileCoords.y - tileCoords.y) * bbox.getHeight();
   double maxx = minx + bbox.getWidth() * 3;
   double maxy = miny + bbox.getHeight() * 3;
   return new Envelope(minx, maxx, miny, maxy);
 }
Пример #20
0
  /*
   * returns a two element array, where each element is list.
   * the first list represents x-coordinates of vertical grid lines, and
   * the second list represents y coordinates of horizintal grid lines.
   */
  private List<Double>[] chooseGridLines(Envelope bounds) {
    double[] gridSizeChoices = {
      1, 2, 5, 10, 25, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000
    };
    int preferredNumberOfGridLines = 2; // approximately, but +/- a couple is okay

    double xSizeGuess = (bounds.getMaxX() - bounds.getMinX()) / preferredNumberOfGridLines;
    double xSize = findClosest(gridSizeChoices, xSizeGuess);

    double ySizeGuess = (bounds.getMaxY() - bounds.getMinY()) / preferredNumberOfGridLines;
    double ySize = findClosest(gridSizeChoices, ySizeGuess);

    double max = Math.max(xSize, ySize);
    xSize = max;
    ySize = max;

    // make list of all the x-coordinates (vertical grid lines)
    double firstX = Math.round(bounds.getMinX() / xSize) * xSize;
    if (firstX > bounds.getMinX()) {
      firstX -= xSize;
    }
    List xList = new ArrayList();
    double xCoord = firstX;
    while (xCoord < bounds.getMaxX() + xSize) {
      xList.add(xCoord);
      xCoord += xSize;
    }

    // make list of all the y-coordinates (hortizontal grid lines)
    double firstY = Math.round(bounds.getMaxY() / ySize) * ySize;
    if (firstY < bounds.getMaxY()) {
      firstY += ySize;
    }
    List yList = new ArrayList();
    double yCoord = firstY;
    while (yCoord > bounds.getMinY() - ySize) {
      yList.add(yCoord);
      yCoord -= ySize;
    }

    List[] result = {xList, yList};
    return result;
  }
Пример #21
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;
  }
Пример #22
0
  /**
   * Computes the distance between this and another <code>Envelope</code>. The distance between
   * overlapping Envelopes is 0. Otherwise, the distance is the Euclidean distance between the
   * closest points.
   */
  @Override
  public double distance(final Envelope env) {
    if (intersects(env)) {
      return 0;
    }

    double dx = 0.0;
    if (getMaxX() < env.getMinX()) {
      dx = env.getMinX() - getMaxX();
    } else if (getMinX() > env.getMaxX()) {
      dx = getMinX() - env.getMaxX();
    }

    double dy = 0.0;
    if (getMaxY() < env.getMinY()) {
      dy = env.getMinY() - getMaxY();
    } else if (getMinY() > env.getMaxY()) {
      dy = getMinY() - env.getMaxY();
    }

    double dz = 0.0;
    double otherMinZ = getMinZOf(env);
    double otherMaxZ = getMaxZOf(env);
    if (maxz < otherMinZ) {
      dz = otherMinZ - maxz;
    } else if (minz > otherMaxZ) {
      dz = minz - otherMaxZ;
    }

    // if either is zero, the envelopes overlap either vertically or
    // horizontally
    if (dx == 0.0 && dz == 0.0) {
      return dy;
    }
    if (dy == 0.0 && dz == 0.0) {
      return dx;
    }
    if (dx == 0.0 && dy == 0.0) {
      return dz;
    }
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
  }
Пример #23
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;
  }
Пример #24
0
  /**
   * Given an envelope and origin, find the tile coordinate (row,col)
   *
   * @param env
   * @param origin
   * @return
   */
  Point getTileCoordinates(Envelope env, Point2D origin) {
    // this was using the low left corner and Math.round, but turned
    // out to be fragile when fairly zoomed in. Using the tile center
    // and then flooring the division seems to work much more reliably.
    double centerx = env.getMinX() + env.getWidth() / 2;
    double centery = env.getMinY() + env.getHeight() / 2;
    int x = (int) Math.floor((centerx - origin.getX()) / env.getWidth());
    int y = (int) Math.floor((centery - origin.getY()) / env.getWidth());

    return new Point(x, y);
  }
 boolean tooSmallOnScreen(Envelope env) {
   double[] d = new double[] {env.getMinX(), env.getMinY(), env.getMaxX(), env.getMaxY()};
   getMap().getViewportModel().worldToScreenTransform().transform(d, 0, d, 0, 2);
   Rectangle r =
       new Rectangle(
           (int) d[0], (int) d[1], (int) Math.abs(d[2] - d[0]), (int) Math.abs(d[3] - d[1]));
   return (double) r.getWidth()
           < getMap().getRenderManager().getMapDisplay().getWidth() / (double) 16
       && (double) r.getHeight()
           < getMap().getRenderManager().getMapDisplay().getHeight() / (double) 16;
 }
Пример #26
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();
    }
  }
Пример #27
0
  @Override
  public Number[] getScope(int dimension) throws DriverException {
    if (cachedScope == null) {
      boolean open = isOpen();
      if (!open) {
        open();
      }
      for (int i = 0; i < getRowCount(); i++) {
        Metadata m = getMetadata();
        for (int j = 0; j < m.getFieldCount(); j++) {
          int typeCode = m.getFieldType(j).getTypeCode();
          Envelope r = null;
          if ((typeCode & Type.GEOMETRY) != 0) {
            Value v = getFieldValue(i, j);
            if ((v != null) && (!v.isNull())) {
              r = v.getAsGeometry().getEnvelopeInternal();
            }
          } else if (typeCode == Type.RASTER) {
            Value v = getFieldValue(i, j);
            if ((v != null) && (!v.isNull())) {
              r = v.getAsRaster().getMetadata().getEnvelope();
            }
          } else if (typeCode == Type.STREAM) {
            Value v = getFieldValue(i, j);
            if ((v != null) && (!v.isNull())) {
              r = v.getAsStream().getEnvelope();
            }
          }
          if (r != null) {
            if (cachedScope == null) {
              cachedScope = new Envelope(r);
            } else {
              cachedScope.expandToInclude(r);
            }
          }
        }
      }
      if (!open) {
        close();
      }
    }

    if (cachedScope == null) {
      return new Number[] {0, 0};
    } else {
      if (dimension == DataSet.X) {
        return new Number[] {cachedScope.getMinX(), cachedScope.getMaxX()};
      } else if (dimension == DataSet.Y) {
        return new Number[] {cachedScope.getMinY(), cachedScope.getMaxY()};
      } else {
        throw new UnsupportedOperationException("Not yet implemented");
      }
    }
  }
Пример #28
0
    /**
     * Returns a {@link CoordinateSequence} for the {@code coordinates} property so its handled by a
     * {@link GMLCoordinatesTypeBinding} at encoding time as {@code gml:coordinates} that Ionic
     * understands
     */
    @Override
    public Object getProperty(Object object, QName name) throws Exception {
      Envelope e = (Envelope) object;
      if (GML.coordinates.equals(name)) {
        double[] seq = {e.getMinX(), e.getMinY(), e.getMaxX(), e.getMaxY()};
        CoordinateSequence coords = new PackedCoordinateSequence.Double(seq, 2);
        return coords;
      }

      return null;
    }
Пример #29
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);
  }
Пример #30
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);
  }