Java Code Examples for org.locationtech.spatial4j.shape.Shape#getBoundingBox()

The following examples show how to use org.locationtech.spatial4j.shape.Shape#getBoundingBox() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpatialArgs.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the distance given a shape and the {@code distErrPct}.  The
 * algorithm is the fraction of the distance from the center of the query
 * shape to its closest bounding box corner.
 *
 * @param shape Mandatory.
 * @param distErrPct 0 to 0.5
 * @param ctx Mandatory
 * @return A distance (in degrees).
 */
public static double calcDistanceFromErrPct(Shape shape, double distErrPct, SpatialContext ctx) {
  if (distErrPct < 0 || distErrPct > 0.5) {
    throw new IllegalArgumentException("distErrPct " + distErrPct + " must be between [0 to 0.5]");
  }
  if (distErrPct == 0 || shape instanceof Point) {
    return 0;
  }
  Rectangle bbox = shape.getBoundingBox();
  //Compute the distance from the center to a corner.  Because the distance
  // to a bottom corner vs a top corner can vary in a geospatial scenario,
  // take the closest one (greater precision).
  Point ctr = bbox.getCenter();
  double y = (ctr.getY() >= 0 ? bbox.getMaxY() : bbox.getMinY());
  double diagonalDist = ctx.getDistCalc().distance(ctr, bbox.getMaxX(), y);
  return diagonalDist * distErrPct;
}
 
Example 2
Source File: SpatialPrefixTreeTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testCellTraverse() {
  trie = new GeohashPrefixTree(ctx,4);

  Cell prevC = null;
  Cell c = trie.getWorldCell();
  assertEquals(0, c.getLevel());
  assertEquals(ctx.getWorldBounds(), c.getShape());
  while (c.getLevel() < trie.getMaxLevels()) {
    prevC = c;
    List<Cell> subCells = new ArrayList<>();
    CellIterator subCellsIter = c.getNextLevelCells(null);
    while (subCellsIter.hasNext()) {
      subCells.add(subCellsIter.next());
    }
    c = subCells.get(random().nextInt(subCells.size()-1));

    assertEquals(prevC.getLevel()+1,c.getLevel());
    Rectangle prevNShape = (Rectangle) prevC.getShape();
    Shape s = c.getShape();
    Rectangle sbox = s.getBoundingBox();
    assertTrue(prevNShape.getWidth() > sbox.getWidth());
    assertTrue(prevNShape.getHeight() > sbox.getHeight());
  }
}
 
Example 3
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected Shape gridSnap(Shape snapMe) {
  if (snapMe == null)
    return null;
  if (snapMe instanceof ShapePair) {
    ShapePair me = (ShapePair) snapMe;
    return new ShapePair(gridSnap(me.shape1), gridSnap(me.shape2), me.biasContainsThenWithin);
  }
  if (snapMe instanceof Point) {
    snapMe = snapMe.getBoundingBox();
  }
  //The next 4 lines mimic PrefixTreeStrategy.createIndexableFields()
  double distErrPct = ((PrefixTreeStrategy) strategy).getDistErrPct();
  double distErr = SpatialArgs.calcDistanceFromErrPct(snapMe, distErrPct, ctx);
  int detailLevel = grid.getLevelForDistance(distErr);
  CellIterator cells = grid.getTreeCellIterator(snapMe, detailLevel);

  //calc bounding box of cells.
  List<Shape> cellShapes = new ArrayList<>(1024);
  while (cells.hasNext()) {
    Cell cell = cells.next();
    if (!cell.isLeaf())
      continue;
    cellShapes.add(cell.getShape());
  }
  return new ShapeCollection<>(cellShapes, ctx).getBoundingBox();
}
 
Example 4
Source File: PortedSolr3Test.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void _checkHits(boolean bbox, Point pt, double distKM, int assertNumFound, int... assertIds) {
  SpatialOperation op = SpatialOperation.Intersects;
  double distDEG = DistanceUtils.dist2Degrees(distKM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
  Shape shape = shapeFactory.circle(pt, distDEG);
  if (bbox)
    shape = shape.getBoundingBox();

  SpatialArgs args = new SpatialArgs(op,shape);
  //args.setDistPrecision(0.025);
  Query query = strategy.makeQuery(args);
  SearchResults results = executeQuery(query, 100);
  assertEquals(""+shape,assertNumFound,results.numFound);
  if (assertIds != null) {
    Set<Integer> resultIds = new HashSet<>();
    for (SearchResult result : results.results) {
      resultIds.add(Integer.valueOf(result.document.get("id")));
    }
    for (int assertId : assertIds) {
      assertTrue("has " + assertId, resultIds.contains(assertId));
    }
  }
}
 
Example 5
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Optionally converts points to circles, and optionally bbox'es result.
 */
public static ShapeConverter makeShapeConverter(final SpatialStrategy spatialStrategy,
                                                Config config, String configKeyPrefix) {
  //by default does no conversion
  final double radiusDegrees = config.get(configKeyPrefix+"radiusDegrees", 0.0);
  final double plusMinus = config.get(configKeyPrefix+"radiusDegreesRandPlusMinus", 0.0);
  final boolean bbox = config.get(configKeyPrefix + "bbox", false);

  return new ShapeConverter() {
    @Override
    public Shape convert(Shape shape) {
      if (shape instanceof Point && (radiusDegrees != 0.0 || plusMinus != 0.0)) {
        Point point = (Point)shape;
        double radius = radiusDegrees;
        if (plusMinus > 0.0) {
          Random random = new Random(point.hashCode());//use hashCode so it's reproducibly random
          radius += random.nextDouble() * 2 * plusMinus - plusMinus;
          radius = Math.abs(radius);//can happen if configured plusMinus > radiusDegrees
        }
        shape = spatialStrategy.getSpatialContext().makeCircle(point, radius);
      }
      if (bbox)
        shape = shape.getBoundingBox();
      return shape;
    }
  };
}
 
Example 6
Source File: AbstractSpatialFieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Implemented for compatibility with geofilt &amp; bbox query parsers:
 * {@link SpatialQueryable}.
 */
@Override
public Query createSpatialQuery(QParser parser, SpatialOptions options) {
  Point pt = SpatialUtils.parsePointSolrException(options.pointStr, ctx);

  double distDeg = DistanceUtils.dist2Degrees(options.distance, options.radius);

  Shape shape = ctx.makeCircle(pt, distDeg);
  if (options.bbox)
    shape = shape.getBoundingBox();

  SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, shape);
  return getQueryFromSpatialArgs(parser, options.field, spatialArgs);
}
 
Example 7
Source File: SpatialOperation.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public boolean evaluate(Shape indexedShape, Shape queryShape) {
  Rectangle bbox = indexedShape.getBoundingBox();
  return bbox.relate(queryShape) == SpatialRelation.WITHIN || bbox.equals(queryShape);
}
 
Example 8
Source File: TestBBoxStrategy.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
protected Shape convertShapeFromGetDocuments(Shape shape) {
  return shape.getBoundingBox();
}
 
Example 9
Source File: HiveQueryVisitor.java    From occurrence with Apache License 2.0 4 votes vote down vote up
public void visit(WithinPredicate within) throws QueryBuildingException {
  JtsSpatialContextFactory spatialContextFactory = new JtsSpatialContextFactory();
  spatialContextFactory.normWrapLongitude = true;
  spatialContextFactory.srid = 4326;
  spatialContextFactory.datelineRule = DatelineRule.ccwRect;

  WKTReader reader = new WKTReader(spatialContextFactory.newSpatialContext(), spatialContextFactory);

  try {
    // the geometry must be valid - it was validated in the predicates constructor
    Shape geometry = reader.parse(within.getGeometry());

    builder.append('(');
    String withinGeometry;

    // Add an additional filter to a bounding box around any shapes that aren't quadrilaterals, to speed up the query.
    if (geometry instanceof JtsGeometry && ((JtsGeometry) geometry).getGeom().getNumPoints() != 5) {
      // Use the Spatial4J-fixed geometry; this is split into a multipolygon if it crosses the antimeridian.
      withinGeometry = ((JtsGeometry) geometry).getGeom().toText();

      Rectangle bounds = geometry.getBoundingBox();
      boundingBox(bounds);
      builder.append(CONJUNCTION_OPERATOR);
    } else {
      withinGeometry = within.getGeometry();
    }
    builder.append("contains(\"");
    builder.append(withinGeometry);
    builder.append("\", ");
    builder.append(HiveColumnsUtils.getHiveColumn(DwcTerm.decimalLatitude));
    builder.append(", ");
    builder.append(HiveColumnsUtils.getHiveColumn(DwcTerm.decimalLongitude));
    // Without the "= TRUE", the expression may evaluate to TRUE or FALSE for all records, depending
    // on the data format (ORC, Avro, Parquet, text) of the table (!).
    // We could not reproduce the issue on our test cluster, so it seems safest to include this.
    builder.append(") = TRUE");

    builder.append(')');
  } catch (Exception e) {
    throw new QueryBuildingException(e);
  }
}