Java 类com.vividsolutions.jts.geom.Envelope 实例源码

项目:sumo    文件:ClipProcess.java   
@DescribeResult(name = "result", description = "Clipped feature collection")
public SimpleFeatureCollection execute(
        @DescribeParameter(name = "features", description = "Input feature collection") SimpleFeatureCollection features,
        @DescribeParameter(name = "clip", description = "Geometry to use for clipping (in same CRS as input features)") Geometry clip,
        @DescribeParameter(name = "preserveZ", min=0,description = "Attempt to preserve Z values from the original geometry (interpolate value for new points)") Boolean preserveZ)
        throws ProcessException {
    // only get the geometries in the bbox of the clip
    Envelope box = clip.getEnvelopeInternal();
    String srs = null;
    if(features.getSchema().getCoordinateReferenceSystem() != null) {
        srs = CRS.toSRS(features.getSchema().getCoordinateReferenceSystem());
    }
    BBOX bboxFilter = ff.bbox("", box.getMinX(), box.getMinY(), box.getMaxX(), box.getMaxY(), srs);

    // default value for preserve Z
    if(preserveZ == null) {
        preserveZ = false;
    }

    // return dynamic collection clipping geometries on the fly
    return new ClippingFeatureCollection(features.subCollection(bboxFilter), clip, preserveZ);
}
项目:openrouteservice    文件:RealTrafficDataProvider.java   
public List<TrafficFeatureInfo> getFeatures(Envelope env)
{
    if (env == null)
        return features;

    if (quadTree == null)
        buildQuadTree();

    List<TrafficFeatureInfo> list = quadTree.query(env);
    List<TrafficFeatureInfo> result = new ArrayList<TrafficFeatureInfo>(list.size());

    for(TrafficFeatureInfo tfi : list)
    {
        Envelope fe = tfi.getEnvelope();
        if (fe != null && fe.intersects(env))
            result.add(tfi);
    }

    return result;
}
项目:openrouteservice    文件:PeliasGeocoder.java   
private String applySearchBoundary(String reqParams, SearchBoundary searchBoundary)
{
    if (searchBoundary != null)
    {
        if (searchBoundary instanceof RectSearchBoundary)
        {
            RectSearchBoundary rsb = (RectSearchBoundary)searchBoundary;
            Envelope env = rsb.getRectangle();
            reqParams += "&boundary.rect.min_lat=" + env.getMinY() + "&boundary.rect.min_lon=" + env.getMinX() + "&boundary.rect.max_lat=" + env.getMaxY() + "&boundary.rect.max_lon=" + env.getMaxX();
        }
        else if (searchBoundary instanceof CircleSearchBoundary)
        {
            CircleSearchBoundary csb = (CircleSearchBoundary)searchBoundary;
            reqParams += "&boundary.circle.lat=" + csb.getLatitude() + "&boundary.circle.lon=" + csb.getLongitude() + "&boundary.circle.radius=" + csb.getRadius();
        }
    }

    return reqParams;
}
项目:logicaldecoding    文件:GWCInvalidator.java   
private void postSeedRequest(Envelope envelope) {

        String gwcurl = gwcBaseUrl + "seed/" + layername + ".json";

        Bounds bounds = new Bounds(new Coordinates(envelope.getMinX(), envelope.getMinY(), envelope.getMaxX(),
                envelope.getMaxY()));
        Srs srs = new Srs(epsgCode);
        SeedRequest request = new SeedRequest(layername, bounds, srs, zoomStart, zoomStop, imageFormat, operation,
                numThreads);

        HttpEntity<GwcSeedDAO> httpentity = new HttpEntity<GwcSeedDAO>(new GwcSeedDAO(request), createHeaders(
                gwcUserName, gwcPassword));
        ResponseEntity response = template.exchange(gwcurl, HttpMethod.POST, httpentity, String.class);
        HttpStatus returncode = response.getStatusCode();
        if (!returncode.is2xxSuccessful()) {
            log.warn("HTTP Call to " + gwcurl + " was not successfull, Status code: " + response.getStatusCode());
        }
        else {
            log.debug("HTTP Call to "+ gwcurl + "succeeded");
        }

    }
项目:Earth    文件:CascadedPolygonUnion.java   
private Geometry unionOptimized(Geometry g0, Geometry g1) {
        Envelope g0Env = g0.getEnvelopeInternal();
        Envelope g1Env = g1.getEnvelopeInternal();
        //*
        if (!g0Env.intersects(g1Env)) {
            Geometry combo = GeometryCombiner.combine(g0, g1);
//          System.out.println("Combined");
//          System.out.println(combo);
            return combo;
        }
        //*/
//      System.out.println(g0.getNumGeometries() + ", " + g1.getNumGeometries());

        if (g0.getNumGeometries() <= 1 && g1.getNumGeometries() <= 1) {
            return this.unionActual(g0, g1);
        }

        // for testing...
//      if (true) return g0.union(g1);

        Envelope commonEnv = g0Env.intersection(g1Env);
        return this.unionUsingEnvelopeIntersection(g0, g1, commonEnv);

//      return UnionInteracting.union(g0, g1);
    }
项目:Earth    文件:RectangleIntersects.java   
@Override
protected void visit(Geometry geom) {
    /**
     * It may be the case that the rectangle and the
     * envelope of the geometry component are disjoint,
     * so it is worth checking this simple condition.
     */
    Envelope elementEnv = geom.getEnvelopeInternal();
    if (!this.rectEnv.intersects(elementEnv)) {
        return;
    }

    // check segment intersections
    // get all lines from geometry component
    // (there may be more than one if it's a multi-ring polygon)
    List lines = LinearComponentExtracter.getLines(geom);
    this.checkIntersectionWithLineStrings(lines);
}
项目:geoxygene    文件:QuadTreeJts.java   
@SuppressWarnings("unchecked")
@Override
public Collection<Feat> select(IGeometry geometry) {
  IEnvelope egeox = geometry.getEnvelope();
  Envelope envelopeJts = new Envelope(egeox.maxX(), egeox.minX(),
      egeox.maxY(), egeox.minY());
  List<Integer> indexes = quad.query(envelopeJts);
  Collection<Feat> result = new HashSet<Feat>();
  // System.out.println(indexes.size());
  for (int ind : indexes) {
    Feat f = collection.get(ind);
    if (f.getGeom().intersects(geometry))
      result.add(f);
  }
  return result;
}
项目:Earth    文件:BufferResultValidator.java   
private void checkEnvelope() {
    if (this.distance < 0.0) {
        return;
    }

    double padding = this.distance * MAX_ENV_DIFF_FRAC;
    if (padding == 0.0) {
        padding = 0.001;
    }

    Envelope expectedEnv = new Envelope(this.input.getEnvelopeInternal());
    expectedEnv.expandBy(this.distance);

    Envelope bufEnv = new Envelope(this.result.getEnvelopeInternal());
    bufEnv.expandBy(padding);

    if (!bufEnv.contains(expectedEnv)) {
        this.isValid = false;
        this.errorMsg = "Buffer envelope is incorrect";
        this.errorIndicator = this.input.getFactory().toGeometry(bufEnv);
    }
    this.report("Envelope");
}
项目:Earth    文件:BufferOp.java   
/**
 * Compute a scale factor to limit the precision of
 * a given combination of Geometry and buffer distance.
 * The scale factor is determined by
 * the number of digits of precision in the (geometry + buffer distance),
 * limited by the supplied <code>maxPrecisionDigits</code> value.
 * <p>
 * The scale factor is based on the absolute magnitude of the (geometry + buffer distance).
 * since this determines the number of digits of precision which must be handled.
 *
 * @param g the Geometry being buffered
 * @param distance the buffer distance
 * @param maxPrecisionDigits the max # of digits that should be allowed by
 * the precision determined by the computed scale factor
 * @return a scale factor for the buffer computation
 */
private static double precisionScaleFactor(Geometry g,
                                           double distance,
                                           int maxPrecisionDigits) {
    Envelope env = g.getEnvelopeInternal();
    double envMax = MathUtil.max(
            Math.abs(env.getMaxX()),
            Math.abs(env.getMaxY()),
            Math.abs(env.getMinX()),
            Math.abs(env.getMinY())
    );

    double expandByDistance = distance > 0.0 ? distance : 0.0;
    double bufEnvMax = envMax + 2 * expandByDistance;

    // the smallest power of 10 greater than the buffer envelope
    int bufEnvPrecisionDigits = (int) (Math.log(bufEnvMax) / Math.log(10) + 1.0);
    int minUnitLog10 = maxPrecisionDigits - bufEnvPrecisionDigits;

    double scaleFactor = Math.pow(10.0, minUnitLog10);
    return scaleFactor;
}
项目:geoxygene    文件:RenderGL11Util.java   
/**
 * @param obj
 *            The FT_coverage to render This method shall be reworked.
 */
public static void paint(final RasterSymbolizer symbolizer, final IFeature obj, final Viewport viewport, final double opacity) {
    FT_Coverage fcoverage = (FT_Coverage) obj;
    try {
        GridCoverage2D coverage = fcoverage.coverage();
        IEnvelope view = viewport.getEnvelopeInModelCoordinates();
        Envelope renderEnvelope = new Envelope(view.minX(), view.maxX(), view.minY(), view.maxY());
        GridCoverageRenderer renderer = new GridCoverageRenderer(coverage.getCoordinateReferenceSystem(), renderEnvelope, viewport.getLayerViewPanels()
                .iterator().next().getVisibleRect(), null);
        org.geotools.styling.RasterSymbolizer s = new StyleBuilder().createRasterSymbolizer();
        s.setOpacity(new FilterFactoryImpl().literal(opacity * symbolizer.getOpacity()));
        logger.warn("Replace by a GL function");
        // renderer.paint(coverage, s);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return;
}
项目:Earth    文件:Quadtree.java   
/**
 * Ensure that the envelope for the inserted item has non-zero extents.
 * Use the current minExtent to pad the envelope, if necessary
 */
public static Envelope ensureExtent(Envelope itemEnv, double minExtent) {
    //The names "ensureExtent" and "minExtent" are misleading -- sounds like
    //this method ensures that the extents are greater than minExtent.
    //Perhaps we should rename them to "ensurePositiveExtent" and "defaultExtent".
    //[Jon Aquino]
    double minx = itemEnv.getMinX();
    double maxx = itemEnv.getMaxX();
    double miny = itemEnv.getMinY();
    double maxy = itemEnv.getMaxY();
    // has a non-zero extent
    if (minx != maxx && miny != maxy) {
        return itemEnv;
    }

    // pad one or both extents
    if (minx == maxx) {
        minx = minx - minExtent / 2.0;
        maxx = minx + minExtent / 2.0;
    }
    if (miny == maxy) {
        miny = miny - minExtent / 2.0;
        maxy = miny + minExtent / 2.0;
    }
    return new Envelope(minx, maxx, miny, maxy);
}
项目:Earth    文件:VoronoiDiagramBuilder.java   
private void create() {
    if (this.subdiv != null) {
        return;
    }

    Envelope siteEnv = DelaunayTriangulationBuilder.envelope(this.siteCoords);
    this.diagramEnv = siteEnv;
    // add a buffer around the final envelope
    double expandBy = Math.max(this.diagramEnv.getWidth(), this.diagramEnv.getHeight());
    this.diagramEnv.expandBy(expandBy);
    if (this.clipEnv != null) {
        this.diagramEnv.expandToInclude(this.clipEnv);
    }

    List vertices = DelaunayTriangulationBuilder.toVertices(this.siteCoords);
    this.subdiv = new QuadEdgeSubdivision(siteEnv, this.tolerance);
    IncrementalDelaunayTriangulator triangulator = new IncrementalDelaunayTriangulator(this.subdiv);
    triangulator.insertSites(vertices);
}
项目:Earth    文件:VoronoiDiagramBuilder.java   
private static Geometry clipGeometryCollection(Geometry geom, Envelope clipEnv) {
    Geometry clipPoly = geom.getFactory().toGeometry(clipEnv);
    List clipped = new ArrayList();
    for (int i = 0; i < geom.getNumGeometries(); i++) {
        Geometry g = geom.getGeometryN(i);
        Geometry result = null;
        // don't clip unless necessary
        if (clipEnv.contains(g.getEnvelopeInternal())) {
            result = g;
        } else if (clipEnv.intersects(g.getEnvelopeInternal())) {
            result = clipPoly.intersection(g);
            // keep vertex key info
            result.setUserData(g.getUserData());
        }

        if (result != null && !result.isEmpty()) {
            clipped.add(result);
        }
    }
    return geom.getFactory().createGeometryCollection(GeometryFactory.toGeometryArray(clipped));
}
项目:Earth    文件:QuadEdgeSubdivision.java   
private void createFrame(Envelope env) {
    double deltaX = env.getWidth();
    double deltaY = env.getHeight();
    double offset = 0.0;
    if (deltaX > deltaY) {
        offset = deltaX * 10.0;
    } else {
        offset = deltaY * 10.0;
    }

    this.frameVertex[0] = new Vertex((env.getMaxX() + env.getMinX()) / 2.0, env
            .getMaxY()
            + offset);
    this.frameVertex[1] = new Vertex(env.getMinX() - offset, env.getMinY() - offset);
    this.frameVertex[2] = new Vertex(env.getMaxX() + offset, env.getMinY() - offset);

    this.frameEnv = new Envelope(this.frameVertex[0].getCoordinate(), this.frameVertex[1]
            .getCoordinate());
    this.frameEnv.expandToInclude(this.frameVertex[2].getCoordinate());
}
项目:Earth    文件:MCPointInRing.java   
@Override
    public boolean isInside(Coordinate pt) {
        this.crossings = 0;

        // test all segments intersected by ray from pt in positive x direction
        Envelope rayEnv = new Envelope(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, pt.y, pt.y);

        this.interval.min = pt.y;
        this.interval.max = pt.y;
        List segs = this.tree.query(this.interval);
//System.out.println("query size = " + segs.size());

        MCSelecter mcSelecter = new MCSelecter(pt);
        for (Object seg : segs) {
            MonotoneChain mc = (MonotoneChain) seg;
            this.testMonotoneChain(rayEnv, mcSelecter, mc);
        }

    /*
     *  p is inside if number of crossings is odd.
     */
        return (crossings % 2) == 1;
    }
项目:Earth    文件:GeometricShapeFactory.java   
/**
 * Creates an elliptical {@link Polygon}.
 * If the supplied envelope is square the
 * result will be a circle.
 *
 * @return an ellipse or circle
 */
public Polygon createEllipse() {

    Envelope env = this.dim.getEnvelope();
    double xRadius = env.getWidth() / 2.0;
    double yRadius = env.getHeight() / 2.0;

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

    Coordinate[] pts = new Coordinate[this.nPts + 1];
    int iPt = 0;
    for (int i = 0; i < this.nPts; i++) {
        double ang = i * (2 * Math.PI / this.nPts);
        double x = xRadius * Math.cos(ang) + centreX;
        double y = yRadius * Math.sin(ang) + centreY;
        pts[iPt++] = this.coord(x, y);
    }
    pts[iPt] = new Coordinate(pts[0]);

    LinearRing ring = this.geomFact.createLinearRing(pts);
    Polygon poly = this.geomFact.createPolygon(ring, null);
    return (Polygon) this.rotate(poly);
}
项目:sldeditor    文件:EnvironmentVariableManagerTest.java   
/**
 * Test method for
 * {@link com.sldeditor.filter.v2.envvar.EnvironmentVariableManager#setWMSEnvVarValues(com.sldeditor.filter.v2.envvar.WMSEnvVarValues)}.
 */
@Test
public void testSetWMSEnvVarValues() {
    EnvironmentVariableManager.getInstance().setWMSEnvVarValues(null);

    WMSEnvVarValues wmsEnvVar = new WMSEnvVarValues();

    wmsEnvVar.setImageHeight(42);
    wmsEnvVar.setImageWidth(454);
    Envelope envelope = new Envelope(1.0, 2.0, 50.0, 51.1);
    ReferencedEnvelope mapBounds = ReferencedEnvelope.create(envelope,
            CoordManager.getInstance().getWGS84());
    wmsEnvVar.setMapBounds(mapBounds);

    EnvironmentVariableManager.getInstance().setWMSEnvVarValues(wmsEnvVar);

    // Update the values again
    WMSEnvVarValues wmsEnvVar2 = new WMSEnvVarValues();
    wmsEnvVar2.setImageHeight(69);
    wmsEnvVar2.setImageWidth(123);
    Envelope envelope2 = new Envelope(-1.0, -2.0, 50.0, 51.1);
    ReferencedEnvelope mapBounds2 = ReferencedEnvelope.create(envelope2,
            CoordManager.getInstance().getWGS84());
    wmsEnvVar2.setMapBounds(mapBounds2);
    EnvironmentVariableManager.getInstance().setWMSEnvVarValues(wmsEnvVar2);
}
项目:Earth    文件:Root.java   
/**
 * insert an item which is known to be contained in the tree rooted at
 * the given QuadNode root.  Lower levels of the tree will be created
 * if necessary to hold the item.
 */
private void insertContained(Node tree, Envelope itemEnv, Object item) {
    Assert.isTrue(tree.getEnvelope().contains(itemEnv));
    /**
     * Do NOT create a new quad for zero-area envelopes - this would lead
     * to infinite recursion. Instead, use a heuristic of simply returning
     * the smallest existing quad containing the query
     */
    boolean isZeroX = IntervalSize.isZeroWidth(itemEnv.getMinX(), itemEnv.getMaxX());
    boolean isZeroY = IntervalSize.isZeroWidth(itemEnv.getMinY(), itemEnv.getMaxY());
    NodeBase node;
    if (isZeroX || isZeroY) {
        node = tree.find(itemEnv);
    } else {
        node = tree.getNode(itemEnv);
    }
    node.add(item);
}
项目:sumo    文件:JTSUtil.java   
/**
 * This is ten times faster than the absolutely correct
 * version above, and it's only off by an average of 1%.
 * Note that the first argument MUST be rectangular, or
 * your results will be meaningless.
 */
public static double fastGetSharedAreaRatio (Geometry geom1, Geometry geom2) {
    Envelope env1 = geom1.getEnvelopeInternal();
    if ((SimplePointInAreaLocator.locate(new Coordinate(env1.getMinX(),env1.getMinY()), geom2) == Location.INTERIOR) &&
        (SimplePointInAreaLocator.locate(new Coordinate(env1.getMaxX(),env1.getMaxY()), geom2) == Location.INTERIOR) &&
        (SimplePointInAreaLocator.locate(new Coordinate(env1.getMaxX(),env1.getMinY()), geom2) == Location.INTERIOR) &&
        (SimplePointInAreaLocator.locate(new Coordinate(env1.getMinX(),env1.getMaxY()), geom2) == Location.INTERIOR)) {
        // I suppose it is possible for a valid polygon geometry
        // to contain all four corners and share considerably less
        // than 100% of its area with the envelope in question.
        // But if you're that worried about correctness you
        // shouldn't be using this method in the first place.
        return 1.0;
    }
    double xInc = env1.getWidth() / 9.0;
    double yInc = env1.getHeight() / 9.0;
    double x = env1.getMinX();
    double y = env1.getMinY();
    double ct = 0;
    for (int i = 0; i < 10; i += 1) {
        y = env1.getMinY();
        for (int j = 0; j < 10; j += 1) {
            if (SimplePointInAreaLocator.locate(new Coordinate(x,y), geom2) == Location.INTERIOR) {
                ct += 1;
            }
            y += yInc;
        }
        x += xInc;
    }
    return (ct / 100.0);
}
项目:graphium    文件:GeometryUtils.java   
public static Polygon createRectangleWithSideLengthInMeters(Point p, double sideLengthMeters) {
    Envelope env = createEnvelopeInMeters(p, sideLengthMeters);
    Coordinate[] coords = new Coordinate[5];
    coords[0] = new Coordinate(env.getMinX(), env.getMinY());
    coords[1] = new Coordinate(env.getMinX(), env.getMaxY());
    coords[2] = new Coordinate(env.getMaxX(), env.getMaxY());
    coords[3] = new Coordinate(env.getMaxX(), env.getMinY());
    coords[4] = new Coordinate(env.getMinX(), env.getMinY());
    return gm.createPolygon(coords);
}
项目:fpm    文件:Splitter.java   
private static Envelope enveloppe(WayContainer way) {
    Envelope env = new Envelope();
    for (WayNode wn : way.getEntity().getWayNodes()) {
        LatLong geohash = Geohash.decodeGeohash(wn.getNodeId());
        env.expandToInclude(geohash.getLon(), geohash.getLat());
    }
    return env;
}
项目:fpm    文件:Splitter.java   
private static Envelope enveloppe(RelationContainer rel) {
    Envelope env = new Envelope();
    for (RelationMember wn : rel.getEntity().getMembers()) {
        LatLong geohash = Geohash.decodeGeohash(wn.getMemberId());
        env.expandToInclude(geohash.getLon(), geohash.getLat());
    }
    return env;
}
项目:vt-support    文件:Fragmenter.java   
/**
 * Add the given geometry to the given tile as defined by the z, x, y values.
 *
 * @param z the tile zoom coordinate value
 * @param x the tile column coordinate value
 * @param y the tile row coordinate value
 * @param layerName name of the layer for the geometry
 * @param geometry  WGS84 geometry
 */
private static void addToStaging(int z, int x, int y, String layerName, Geometry geometry,
                                 Map<Key, JtsMvt> bucket) {
  double[] ul = CoordinateConversion.toLatLon(z, x, y, VT_MIN, VT_MIN, VT_MEASUREMENT_SPACE);
  double[] lr = CoordinateConversion.toLatLon(z, x, y, VT_MAX, VT_MAX, VT_MEASUREMENT_SPACE);

  Envelope tileEnvelope = new Envelope(ul[1], lr[1], ul[0], lr[0]);

  final GeometryFactory geomFactory = new GeometryFactory();

  // Build MVT tile geometry
  // TODO REMOVE HACK
  final TileGeomResult tileGeom = JtsAdapter.createTileGeom(toMercator(geometry),
      toMercator(tileEnvelope), geomFactory, DEFAULT_MVT_PARAMS, ACCEPT_ALL_FILTER);

  if (tileGeom.mvtGeoms.isEmpty()) {
    // System.out.println(String.format("Empty: %d %d %d", z, x, y));
    return;
  }

  // ########################################################
  // # Update TEMP
  // ########################################################
  Key key = new Key(z, x, y);
  if (!bucket.containsKey(key)) {
    bucket.put(key, new JtsMvt(new JtsLayer(layerName)));
  } else if (bucket.get(key).getLayer(layerName) == null) {
    // TODO consider PR
    bucket.get(key).getLayersByName().put(layerName, new JtsLayer(layerName));
    //bucket.get(key).addLayers(new JtsLayer(layerName));
  }

  JtsMvt mvt = bucket.get(key);
  JtsLayer layer = mvt.getLayer(layerName);
  layer.getGeometries().addAll(tileGeom.mvtGeoms); // TODO verify this is ok!!!!
  // ########################################################
  // # EO Update TEMP
  // ########################################################
}
项目:vt-support    文件:Picture.java   
/**
 * Build the picture.
 * @return the built picture as vector tile bytes
 */
public byte[] build() {
  final Envelope tileEnvelope = new Envelope(0d, 4096d, 0d, 4096d);

  // Build MVT
  final VectorTile.Tile.Builder tileBuilder = VectorTile.Tile.newBuilder();

  for (Map.Entry<String, List<Geometry>> layer : layers.entrySet()) {
    String layerName = layer.getKey();
    final List<Geometry> layerGeoms = layer.getValue();

    final TileGeomResult tileGeom = JtsAdapter.createTileGeom(layerGeoms, tileEnvelope,
        geometryFactory, DEFAULT_MVT_PARAMS, ACCEPT_ALL_FILTER);

    // Create MVT layer
    final VectorTile.Tile.Layer.Builder layerBuilder =
        MvtLayerBuild.newLayerBuilder(layerName, DEFAULT_MVT_PARAMS);
    final MvtLayerProps layerProps = new MvtLayerProps();
    final UserDataIgnoreConverter ignoreUserData = new UserDataIgnoreConverter();

    // MVT tile geometry to MVT features
    final List<VectorTile.Tile.Feature> features =
        JtsAdapter.toFeatures(tileGeom.mvtGeoms, layerProps, ignoreUserData);
    layerBuilder.addAllFeatures(features);
    MvtLayerBuild.writeProps(layerBuilder, layerProps);

    // Build MVT layer
    final VectorTile.Tile.Layer vtLayer = layerBuilder.build();
    tileBuilder.addLayers(vtLayer);
  }
  /// Build MVT
  return tileBuilder.build().toByteArray();
}
项目:openrouteservice    文件:PostgreSQLLocationsDataProvider.java   
private PreparedStatement createLocationsStatement(LocationsRequest request, Connection conn, QueryColumnsInfo queryInfo) throws Exception
{
    Geometry geom = request.getGeometry();
    Envelope bbox = request.getBBox();

    byte[] geomBytes = geometryToWKB(geom, bbox);

    // at the end, we add virtual column to store the exact distance. 
    String query = "SELECT " + queryInfo.getQuery1Columns() + " FROM " + _tableName;

    String whereCondition = "";

    String searchCondition = buildSearchFilter(request.getSearchFilter());
    if (!Helper.isEmpty(searchCondition))
        whereCondition += searchCondition;

    String stateText = String.format("SELECT %s FROM ORS_FindLocations('(%s) as tmp', '%s', ?, %.3f, %d) AS %s", queryInfo.getQuery2Columns(), query, whereCondition, request.getRadius(), request.getLimit(), queryInfo.getReturnTable());

    if (request.getSortType() != LocationsResultSortType.NONE)
    {
        if (request.getSortType() == LocationsResultSortType.CATEGORY)
            stateText += " ORDER BY category";
        else if (request.getSortType() == LocationsResultSortType.DISTANCE)
            stateText += " ORDER BY distance";
    }

    PreparedStatement statement = conn.prepareStatement(stateText);    
    statement.setMaxRows(request.getLimit());
    if (geomBytes != null)
        statement.setBytes(1, geomBytes);

    return statement;
}
项目:openrouteservice    文件:PostgreSQLLocationsDataProvider.java   
private PreparedStatement createCategoriesStatement(LocationsRequest request, Connection conn) throws Exception 
{
    String cmdFilter = buildSearchFilter(request.getSearchFilter()); 

    byte[]  geomBytes = null;
    Geometry geom = request.getGeometry();
    Envelope bbox = request.getBBox();

    if (geom != null)
       geomBytes = geometryToWKB(geom, bbox);

    if (bbox != null)
        cmdFilter = addConditions(cmdFilter, buildBboxFilter(bbox));

    String stateText = null;

    if (geom == null)
        stateText = String.format("SELECT category, COUNT(category) AS count FROM %s WHERE (%s) GROUP BY category ORDER BY category", _tableName, cmdFilter);
    else
        stateText = String.format("SELECT * FROM ORS_FindLocationCategories('%s', '%s', ?, %.3f) AS categories(category smallint, count bigint)", _tableName, cmdFilter, request.getRadius());

    PreparedStatement statement = conn.prepareStatement(stateText);
    if (geomBytes != null)
        statement.setBytes(1, geomBytes);

    return statement;
}
项目:openrouteservice    文件:PostgreSQLLocationsDataProvider.java   
private byte[] geometryToWKB(Geometry geom, Envelope bbox) throws IOException
{
    if (geom == null)
        geom = JTS.toGeometry(bbox);

    WKBWriter wkbWriter = new WKBWriter();
    ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
    wkbWriter.write(geom, new OutputStreamOutStream(bytesStream));
    byte[] geomBytes = bytesStream.toByteArray();
    bytesStream.close();

    return geomBytes;
}
项目:openrouteservice    文件:MemSQLLocationsDataProvider.java   
private PreparedStatement createCategoriesStatement(LocationsRequest request, Connection conn) throws Exception 
{
    String cmdFilter = buildSearchFilter("", request.getSearchFilter()); 

    Geometry geom = request.getGeometry();
    Envelope bbox = request.getBBox();
    if (bbox != null)
        cmdFilter += buildBboxFilter(bbox) + (geom == null ? "" : " AND ");

    if (geom != null)
    {
        if (geom instanceof Point)
        {
            Point p = (Point)geom;
            cmdFilter += String.format("GEOGRAPHY_WITHIN_DISTANCE(%s, GEOGRAPHY_POINT(%.7f, %.7f), %.1f)", _geomColumn, p.getCoordinate().x, p.getCoordinate().y, request.getRadius());
        } 
        else 
        {
            WKTWriter wktWriter = new WKTWriter();
            cmdFilter += String.format("GEOGRAPHY_WITHIN_DISTANCE(%s, \"%s\", %.1f)", _geomColumn, wktWriter.write(geom), request.getRadius());
        }
    }

    if (cmdFilter != "")
        cmdFilter = " WHERE " + cmdFilter;

    String stateText = _categoriesQuery.replace("!where_clause!", cmdFilter);

    return conn.prepareStatement(stateText);    
}
项目:openrouteservice    文件:MemSQLLocationsDataProvider.java   
private String buildBboxFilter(Envelope bbox)
{
    String polygon = "'POLYGON((" + bbox.getMinX() + " " + bbox.getMinY() + "," +
            bbox.getMinX() + " " + bbox.getMaxY() + "," + 
            bbox.getMaxX() + " " + bbox.getMaxY() + "," + 
            bbox.getMinY() + " " + bbox.getMaxY() + "," +
            bbox.getMinX() + " " + bbox.getMinY() +"))'";
    return "GEOGRAPHY_INTERSECTS(" + polygon +  "," + _geomColumn + ")";
}
项目:openrouteservice    文件:TrafficFeatureInfo.java   
public Envelope getEnvelope()
{
 if (envelope == null && geometry != null)
  envelope = geometry.getEnvelopeInternal();

 return envelope;
}
项目:openrouteservice    文件:TmcSegmentsCollection.java   
public TmcSegment getClosestSegment(Coordinate c, double thresholdDistance)
{
    if (quadTree == null)
        buildQuadTree();

    Point p = geomFactory.createPoint(c);
    BBox bbox = distanceCalc.createBBox(c.y, c.x, thresholdDistance);
    Envelope env = new Envelope(bbox.minLon, bbox.maxLon, bbox.minLat, bbox.maxLat);

    @SuppressWarnings("unchecked")
    List<TmcSegment> segments = (List<TmcSegment>)(quadTree.query(env));
    double minDistance = Double.MAX_VALUE;
    TmcSegment res = null;
    for( TmcSegment seg : segments)
    {
            Coordinate c1 = DistanceOp.nearestPoints(seg.getGeometry(), p)[0];
        double dist =  distanceCalc.calcDist(c.y, c.x, c1.y, c1.x);

        if (dist < minDistance)
        {
            minDistance = dist;

            if (dist <= thresholdDistance)
                res = seg;
        }
    }

    return res;
}
项目:openrouteservice    文件:AvoidAreasEdgeFilter.java   
public Envelope expandEnvelope(Envelope env)
{
    for (int i = 0; i < coordinates.length; i++ ) {
        env.expandToInclude(coordinates[i]);
    }
    return env;
}
项目:openrouteservice    文件:JTS.java   
public static Polygon toGeometry(final Envelope env, GeometryFactory factory) {
        ensureNonNull("env", env);

        Polygon polygon = factory.createPolygon(
                factory.createLinearRing(new Coordinate[] {
                        new Coordinate(env.getMinX(), env.getMinY()),
                        new Coordinate(env.getMaxX(), env.getMinY()),
                        new Coordinate(env.getMaxX(), env.getMaxY()),
                        new Coordinate(env.getMinX(), env.getMaxY()),
                        new Coordinate(env.getMinX(), env.getMinY()) }), null);

        return polygon;
}
项目:openrouteservice    文件:IsochronesIntersection.java   
public Envelope getEnvelope()
{
    if(_envelope == null)
        _envelope = _geometry.getEnvelopeInternal();

    return _envelope;
}
项目:openrouteservice    文件:IsochroneMap.java   
public IsochroneMap(int travellerId, Coordinate center)
{
    _travellerId = travellerId;
    _center = center;
    _isochrones = new ArrayList<Isochrone>();
    _envelope = new Envelope();
}
项目:openrouteservice    文件:IsochroneUtility.java   
private static List<IsochronesIntersection> computeIntersection(Isochrone isoLine, Integer isoIndex, IsochroneMap isoMap, Integer isoMapIndex, IsochroneMapCollection isochroneMaps, List<Integer> processedPairs)
{
    List<IsochronesIntersection> result = null;
    Envelope isoEnvelope = isoLine.getEnvelope();
    Geometry isoGeometry = isoLine.getGeometry();

    for (int im = isoMapIndex + 1; im < isochroneMaps.size(); im++)
    {
        IsochroneMap isoMap2 =  isochroneMaps.getIsochrone(im);
        if (!Objects.equals(isoMap2, isoMap) && isoMap2.getEnvelope().intersects(isoEnvelope))
        {
            int ii = 0;
            for (Isochrone isoLine2 : isoMap2.getIsochrones()) 
            {
                if (isoEnvelope.intersects(isoLine2.getEnvelope()))
                {
                    Geometry geomIntersection =  isoGeometry.intersection(isoLine2.getGeometry());

                    if (geomIntersection != null && geomIntersection.isEmpty() == false)
                    {
                        if (result == null)
                            result = new ArrayList<IsochronesIntersection>();

                        IsochronesIntersection isoIntersection = new IsochronesIntersection(geomIntersection);
                        isoIntersection.addContourRefs(new Pair<Integer, Integer>(isoMapIndex, isoIndex));
                        isoIntersection.addContourRefs(new Pair<Integer, Integer>(im, ii));

                        result.add(isoIntersection);
                    }
                }

                ii++;
            }
        }
    }

    return result;
}
项目:openrouteservice    文件:IsochroneMapCollection.java   
public Geometry computeIntersection()
{
    if (_isochroneMaps.size() == 0)
        return null;

    if (_isochroneMaps.size() == 1)
        return _isochroneMaps.get(0).getIsochrone(0).getGeometry();

    Isochrone iso = _isochroneMaps.get(0).getIsochrone(0);
    Geometry geomIntersection = iso.getGeometry();
    Envelope envIntersection = iso.getEnvelope();

    for (int i = 1; i < _isochroneMaps.size(); ++i)
    {
        iso = _isochroneMaps.get(i).getIsochrone(0);
        if (envIntersection.intersects(iso.getEnvelope()))
        {
            geomIntersection = geomIntersection.intersection(iso.getGeometry());
            if (geomIntersection == null || geomIntersection.isEmpty())
                return null;
        }
        else
            return null;
    }

    return geomIntersection;
}
项目:ThriftyPaxos    文件:ValueGeometry.java   
/**
 * Get the union.
 *
 * @param r the other geometry
 * @return the union of this geometry envelope and another geometry envelope
 */
public Value getEnvelopeUnion(ValueGeometry r) {
    GeometryFactory gf = new GeometryFactory();
    Envelope mergedEnvelope = new Envelope(getGeometryNoCopy().getEnvelopeInternal());
    mergedEnvelope.expandToInclude(r.getGeometryNoCopy().getEnvelopeInternal());
    return get(gf.toGeometry(mergedEnvelope));
}
项目:ThriftyPaxos    文件:SpatialTreeIndex.java   
private SpatialKey getKey(SearchRow row) {
    if (row == null) {
        return null;
    }
    Value v = row.getValue(columnIds[0]);
    if (v == ValueNull.INSTANCE) {
        return null;
    }
    Geometry g = ((ValueGeometry) v.convertTo(Value.GEOMETRY)).getGeometryNoCopy();
    Envelope env = g.getEnvelopeInternal();
    return new SpatialKey(row.getKey(),
            (float) env.getMinX(), (float) env.getMaxX(),
            (float) env.getMinY(), (float) env.getMaxY());
}
项目:Earth    文件:MonotoneChain.java   
public Envelope getEnvelope() {
    if (this.env == null) {
        Coordinate p0 = this.pts[this.start];
        Coordinate p1 = this.pts[this.end];
        this.env = new Envelope(p0, p1);
    }
    return this.env;
}