Java Code Examples for com.spatial4j.core.context.SpatialContext

The following examples show how to use com.spatial4j.core.context.SpatialContext. These examples are extracted from open source projects. 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
@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 2
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 3
Source Project: Real-Time-Taxi-Dispatch-Simulator   Source File: NavUtils.java    License: 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 4
Source Project: stratio-cassandra   Source File: GeoCircle.java    License: 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 5
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 6
Source Project: orientdb-lucene   Source File: OLuceneNearOperator.java    License: 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 7
Source Project: orientdb-lucene   Source File: OLuceneWithinOperator.java    License: 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 8
Source Project: orientdb-lucene   Source File: OPointShapeFactory.java    License: 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 9
Source Project: orientdb-lucene   Source File: OShapeFactoryImpl.java    License: 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 10
Source Project: orientdb-lucene   Source File: ORectangleShapeFactory.java    License: 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 11
Source Project: orientdb-lucene   Source File: OPolygonShapeFactory.java    License: 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 12
Source Project: incubator-retired-blur   Source File: SpatialArgsParser.java    License: 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 Project: incubator-retired-blur   Source File: SpatialArgsParser.java    License: 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 14
@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 15
@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 16
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 17
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 18
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 19
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 20
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 21
Source Project: Elasticsearch   Source File: XShapeCollection.java    License: Apache License 2.0 4 votes vote down vote up
public XShapeCollection(List<S> shapes, SpatialContext ctx) {
  super(shapes, ctx);
}
 
Example 22
Source Project: linden   Source File: SortConstructor.java    License: 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 23
Source Project: rya   Source File: SpatialSupportInitializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected SpatialContext createSpatialContext() {
    return JtsSpatialContext.GEO;
}
 
Example 24
Source Project: stratio-cassandra   Source File: GeoPoint.java    License: 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 Project: stratio-cassandra   Source File: GeoShapeMapper.java    License: Apache License 2.0 4 votes vote down vote up
public SpatialContext getSpatialContext() {
    return spatialContext;
}
 
Example 26
Source Project: stratio-cassandra   Source File: GeoRectangle.java    License: 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 27
Source Project: incubator-retired-blur   Source File: ShapeReadWriter.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public ShapeReadWriter(SpatialContext ctx) {
  this.ctx = (CTX) ctx;
}
 
Example 28
Source Project: stratio-cassandra   Source File: GeoShape.java    License: 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 Project: orientdb-lucene   Source File: OShapeFactory.java    License: Apache License 2.0 votes vote down vote up
public Shape makeShape(OCompositeKey key,SpatialContext ctx);