com.spatial4j.core.context.SpatialContext Java Examples

The following examples show how to use com.spatial4j.core.context.SpatialContext. 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: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Test
public void test28() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  ShapeReadWriter<SpatialContext> shapeReadWriter = new ShapeReadWriter<SpatialContext>(ctx);
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  String writeSpatialArgs = SpatialArgsParser.writeSpatialArgs(args, shapeReadWriter);

  // This has to be done because of rounding.
  SpatialArgs spatialArgs = SpatialArgsParser.parse(writeSpatialArgs, shapeReadWriter);
  Query q1 = sq(strategy.makeQuery(spatialArgs));
  Query q = parseSq("a.id_gis:\"" + writeSpatialArgs + "\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #2
Source File: SpatialRecursivePrefixTreeStrategyFieldTypeDefinition.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(String fieldNameForThisInstance, Map<String, String> properties, Configuration configuration) {
  _ctx = SpatialContext.GEO;
  _grid = getSpatialPrefixTree(fieldNameForThisInstance, properties);
  boolean docValue = false;
  if (properties.get(DOC_VALUE) != null) {
    docValue = true;
  }
  _strategy = new RecursivePrefixTreeStrategy(_grid, fieldNameForThisInstance, docValue);
  _shapeReadWriter = new ShapeReadWriter<SpatialContext>(_ctx);
  addSupportedIndexedShapes(Shape.class);
  addSupportedOperations(SpatialOperation.IsDisjointTo);
  addSupportedOperations(SpatialOperation.Intersects);
  addSupportedOperations(SpatialOperation.IsWithin);
  addSupportedOperations(SpatialOperation.Contains);
}
 
Example #3
Source File: ORectangleShapeFactory.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Shape makeShape(OCompositeKey key, SpatialContext ctx) {

  Point[] points = new Point[2];
  int i = 0;
  for (Object o : key.getKeys()) {
    List<Number> numbers = (List<Number>) o;
    double lat = ((Double) OType.convert(numbers.get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(numbers.get(1), Double.class)).doubleValue();
    points[i] = ctx.makePoint(lng, lat);
    i++;
  }
  return ctx.makeRectangle(points[0], points[1]);
}
 
Example #4
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test47() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("<a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\">");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #5
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test46() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(bq(bc_m(strategy.makeQuery(args)), bc(tq("rowid", "12345"))));
  Query q = parseSq("<+a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\" rowid:12345>");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #6
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test45() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(bq(bc_m(strategy.makeQuery(args))));
  Query q = parseSq("<+a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\">");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #7
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test30() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #8
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test29() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0km))\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #9
Source File: SpatialPointVectorStrategyFieldTypeDefinition.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(String fieldNameForThisInstance, Map<String, String> properties, Configuration configuration) {
  _ctx = SpatialContext.GEO;
  _strategy = new PointVectorStrategy(_ctx, fieldNameForThisInstance);
  _shapeReadWriter = new ShapeReadWriter<SpatialContext>(_ctx);
  _alternateFieldNames = Arrays.asList(fieldNameForThisInstance + PointVectorStrategy.SUFFIX_X,
      fieldNameForThisInstance + PointVectorStrategy.SUFFIX_Y);
  addSupportedIndexedShapes(Point.class);
  addSupportedOperations(SpatialOperation.Intersects);
}
 
Example #10
Source File: SpatialTermQueryPrefixTreeStrategyFieldTypeDefinition.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(String fieldNameForThisInstance, Map<String, String> properties, Configuration configuration) {
  _ctx = SpatialContext.GEO;
  boolean docValue = false;
  if (properties.get(DOC_VALUE) != null) {
    docValue = true;
  }
  _grid = getSpatialPrefixTree(fieldNameForThisInstance, properties);
  _strategy = new TermQueryPrefixTreeStrategy(_grid, fieldNameForThisInstance, docValue);
  _shapeReadWriter = new ShapeReadWriter<SpatialContext>(_ctx);
  addSupportedIndexedShapes(Point.class);
  addSupportedOperations(SpatialOperation.Intersects);
}
 
Example #11
Source File: SpatialArgsParser.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a string such as "Intersects(-10,20,-8,22) distErrPct=0.025".
 * 
 * @param v
 *          The string to parse. Mandatory.
 * @param shapeReadWriter
 *          The spatial shapeReadWriter. Mandatory.
 * @return Not null.
 * @throws IllegalArgumentException
 *           If there is a problem parsing the string.
 * @throws InvalidShapeException
 *           Thrown from {@link ShapeReadWriter#readShape(String)}
 */
public static SpatialArgs parse(String v, ShapeReadWriter<SpatialContext> shapeReadWriter) throws IllegalArgumentException, InvalidShapeException {
  int idx = v.indexOf('(');
  int edx = v.lastIndexOf(')');

  if (idx < 0 || idx > edx) {
    throw new IllegalArgumentException("missing parens: " + v, null);
  }

  SpatialOperation op = SpatialOperation.get(v.substring(0, idx).trim());

  String body = v.substring(idx + 1, edx).trim();
  if (body.length() < 1) {
    throw new IllegalArgumentException("missing body : " + v, null);
  }

  Shape shape = shapeReadWriter.readShape(body);
  SpatialArgs args = new SpatialArgs(op, shape);

  if (v.length() > (edx + 1)) {
    body = v.substring(edx + 1).trim();
    if (body.length() > 0) {
      Map<String, String> aa = parseMap(body);
      args.setDistErrPct(readDouble(aa.remove(DIST_ERR_PCT)));
      args.setDistErr(readDouble(aa.remove(DIST_ERR)));
      if (!aa.isEmpty()) {
        throw new IllegalArgumentException("unused parameters: " + aa, null);
      }
    }
  }
  args.validate();
  return args;
}
 
Example #12
Source File: SpatialArgsParser.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/** Writes a close approximation to the parsed input format. */
public static String writeSpatialArgs(SpatialArgs args, ShapeReadWriter<SpatialContext> shapeReadWriter) {
  StringBuilder str = new StringBuilder();
  str.append(args.getOperation().getName());
  str.append('(');
  str.append(shapeReadWriter.writeShape(args.getShape()));
  if (args.getDistErrPct() != null)
    str.append(" distErrPct=").append(String.format(Locale.ROOT, "%.2f%%", args.getDistErrPct() * 100d));
  if (args.getDistErr() != null)
    str.append(" distErr=").append(args.getDistErr());
  str.append(')');
  return str.toString();
}
 
Example #13
Source File: OPolygonShapeFactory.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Shape makeShape(OCompositeKey key, SpatialContext ctx) {

  SpatialContext ctx1 = JtsSpatialContext.GEO;
  String value = key.getKeys().get(0).toString();

  try {
    return ctx1.getWktShapeParser().parse(value);
  } catch (ParseException e) {
    OLogManager.instance().error(this, "Error on making shape", e);
  }
  return null;
}
 
Example #14
Source File: NavUtils.java    From Real-Time-Taxi-Dispatch-Simulator with MIT License 5 votes vote down vote up
/**
 * Returns distance (in meters) between 2 points.
 *
 * @param point1 Must not be null
 * @param point2 Must not be null
 * @return distance in meters
 */
public static double getDistance(Point point1, Point point2) {
    Assert.notNull(point1, "point1 must not be null");
    Assert.notNull(point2, "point2 must not be null");

    final SpatialContext ctx = SpatialContext.GEO;
    com.spatial4j.core.shape.Point p1 = ctx.makePoint(point1.getLongitude(), point1.getLatitude());
    com.spatial4j.core.shape.Point p2 = ctx.makePoint(point2.getLongitude(), point2.getLatitude());

    return DistanceUtils.degrees2Dist(ctx.getDistCalc().distance(p1, p2), DistanceUtils.EARTH_MEAN_RADIUS_KM) * 1000;
}
 
Example #15
Source File: OShapeFactoryImpl.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Shape makeShape(OCompositeKey key, SpatialContext ctx) {
  for (OShapeFactory f : factories.values()) {
    if (f.canHandle(key)) {
      return f.makeShape(key, ctx);
    }
  }
  return null;
}
 
Example #16
Source File: OPointShapeFactory.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Shape makeShape(OCompositeKey key, SpatialContext ctx) {
  double lat = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(0), Double.class)).doubleValue();
  double lng = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(1), Double.class)).doubleValue();
  return ctx.makePoint(lng, lat);

}
 
Example #17
Source File: OLuceneWithinOperator.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Object evaluateRecord(OIdentifiable iRecord, ODocument iCurrentResult, OSQLFilterCondition iCondition, Object iLeft,
    Object iRight, OCommandContext iContext) {
  List<Number> left = (List<Number>) iLeft;

  double lat = left.get(0).doubleValue();
  double lon = left.get(1).doubleValue();

  Shape shape = SpatialContext.GEO.makePoint(lon, lat);

  Shape shape1 = shapeFactory.makeShape(new OSpatialCompositeKey((List<?>) iRight), SpatialContext.GEO);

  return shape.relate(shape1) == SpatialRelation.WITHIN;
}
 
Example #18
Source File: OLuceneNearOperator.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public Object evaluateRecord(OIdentifiable iRecord, ODocument iCurrentResult, OSQLFilterCondition iCondition, Object iLeft,
    Object iRight, OCommandContext iContext) {

  List<Number> left = (List<Number>) iLeft;

  double lat = left.get(0).doubleValue();
  double lon = left.get(1).doubleValue();

  Shape shape = SpatialContext.GEO.makePoint(lon, lat);
  List<Number> right = (List<Number>) iRight;

  double lat1 =  right.get(0).doubleValue();
  double lon1 =  right.get(1).doubleValue();
  Shape shape1 = SpatialContext.GEO.makePoint(lon1, lat1);

  Map map = (Map) right.get(2);
  double distance = 0;

  Number n = (Number) map.get("maxDistance");
  if (n != null) {
    distance = n.doubleValue();
  }
  Point p = (Point) shape1;
  Circle circle = SpatialContext.GEO.makeCircle(p.getX(), p.getY(),
      DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  double docDistDEG = SpatialContext.GEO.getDistCalc().distance((Point) shape, p);
  final double docDistInKM = DistanceUtils.degrees2Dist(docDistDEG, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM);
  iContext.setVariable("distance", docDistInKM);
  return shape.relate(circle) == SpatialRelation.WITHIN;
}
 
Example #19
Source File: OLuceneSpatialIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
public OLuceneSpatialIndexManager(OShapeFactory factory) {
  super();
  this.ctx = SpatialContext.GEO;
  this.factory = factory;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, 11);
  this.strategy = new RecursivePrefixTreeStrategy(grid, "location");
}
 
Example #20
Source File: GeoCircle.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Shape toSpatial4j(SpatialContext spatialContext) {
    double kms = distance.getValue(GeoDistanceUnit.KILOMETRES);
    double d = DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);
    return spatialContext.makeCircle(longitude, latitude, d);
}
 
Example #21
Source File: ShapeReadWriter.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public ShapeReadWriter(SpatialContext ctx) {
  this.ctx = (CTX) ctx;
}
 
Example #22
Source File: GeoRectangle.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public com.spatial4j.core.shape.Shape toSpatial4j(SpatialContext spatialContext) {
    return spatialContext.makeRectangle(minLongitude, maxLongitude, minLatitude, maxLatitude);
}
 
Example #23
Source File: GeoShapeMapper.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public SpatialContext getSpatialContext() {
    return spatialContext;
}
 
Example #24
Source File: GeoPoint.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public com.spatial4j.core.shape.Shape toSpatial4j(SpatialContext spatialContext) {
    return spatialContext.makePoint(longitude, latitude);
}
 
Example #25
Source File: SpatialSupportInitializer.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
protected SpatialContext createSpatialContext() {
    return JtsSpatialContext.GEO;
}
 
Example #26
Source File: SortConstructor.java    From linden with Apache License 2.0 4 votes vote down vote up
public static Sort constructSort(LindenSearchRequest request, IndexSearcher indexSearcher, LindenConfig config) throws IOException {
  if (!request.isSetSort())
    return null;

  LindenSort lindenSort = request.getSort();
  SortField[] sortFields = new SortField[lindenSort.getFieldsSize()];
  for (int i = 0; i < lindenSort.getFieldsSize(); ++i) {
    LindenSortField field = lindenSort.getFields().get(i);
    SortField.Type type = SortField.Type.STRING;
    boolean isReverse = field.isReverse();
    switch (field.getType()) {
      case STRING:
        type = SortField.Type.STRING;
        break;
      case DOUBLE:
        type = SortField.Type.DOUBLE;
        break;
      case FLOAT:
        type = SortField.Type.FLOAT;
        break;
      case INTEGER:
        type = SortField.Type.INT;
        break;
      case LONG:
        type = SortField.Type.LONG;
        break;
      case SCORE:
        type = SortField.Type.SCORE;
        isReverse = !isReverse;
        break;
      case DISTANCE:
        if (request.isSetSpatialParam()) {
          Point point = SpatialContext.GEO.makePoint(
              request.getSpatialParam().getCoordinate().getLongitude(),
              request.getSpatialParam().getCoordinate().getLatitude());
          ValueSource valueSource = config.getSpatialStrategy().makeDistanceValueSource(point, DistanceUtils.DEG_TO_KM);
          sortFields[i] = valueSource.getSortField(false).rewrite(indexSearcher);
        }
        continue;
    }
    sortFields[i] = new SortField(field.getName(), type, isReverse);
  }
  return new Sort(sortFields);
}
 
Example #27
Source File: XShapeCollection.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public XShapeCollection(List<S> shapes, SpatialContext ctx) {
  super(shapes, ctx);
}
 
Example #28
Source File: GeoShape.java    From stratio-cassandra with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the {@link com.spatial4j.core.shape.Shape} representation of this geographical shape.
 *
 * @param spatialContext The spatial context to be used.
 * @return The {@link com.spatial4j.core.shape.Shape} representation of this geographical shape.
 */
public abstract com.spatial4j.core.shape.Shape toSpatial4j(SpatialContext spatialContext);
 
Example #29
Source File: OShapeFactory.java    From orientdb-lucene with Apache License 2.0 votes vote down vote up
public Shape makeShape(OCompositeKey key,SpatialContext ctx);