Java Code Examples for com.spatial4j.core.shape.Point

The following examples show how to use com.spatial4j.core.shape.Point. 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
public Object searchIntersect(OCompositeKey key, double distance, OCommandContext context) throws IOException {

    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();
    SpatialOperation operation = SpatialOperation.Intersects;

    Point p = ctx.makePoint(lng, lat);
    SpatialArgs args = new SpatialArgs(operation, ctx.makeCircle(lng, lat,
        DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = strategy.makeFilter(args);
    IndexSearcher searcher = getSearcher();
    ValueSource valueSource = strategy.makeDistanceValueSource(p);
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);

    return new LuceneResultSet(this,
        new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter, distSort).setSpatialArgs(args));
  }
 
Example 2
Source Project: incubator-retired-blur   Source File: ShapeReadWriter.java    License: Apache License 2.0 6 votes vote down vote up
/** Overloaded to provide a number format. */
public String writeShape(Shape shape, NumberFormat nf) {
  if (shape instanceof Point) {
    Point point = (Point) shape;
    return nf.format(point.getX()) + " " + nf.format(point.getY());
  } else if (shape instanceof Rectangle) {
    Rectangle rect = (Rectangle) shape;
    return nf.format(rect.getMinX()) + " " + nf.format(rect.getMinY()) + " " + nf.format(rect.getMaxX()) + " "
        + nf.format(rect.getMaxY());
  } else if (shape instanceof Circle) {
    Circle c = (Circle) shape;
    return "Circle(" + nf.format(c.getCenter().getX()) + " " + nf.format(c.getCenter().getY()) + " " + "d="
        + nf.format(c.getRadius()) + ")";
  }
  return shape.toString();
}
 
Example 3
Source Project: incubator-retired-blur   Source File: PrefixTreeStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ValueSource makeDistanceValueSource(Point queryPoint) {
  PointPrefixTreeFieldCacheProvider p = provider.get(getFieldName());
  if (p == null) {
    synchronized (this) {// double checked locking idiom is okay since
                         // provider is threadsafe
      p = provider.get(getFieldName());
      if (p == null) {
        p = new PointPrefixTreeFieldCacheProvider(grid, getFieldName(), defaultFieldValuesArrayLen);
        provider.put(getFieldName(), p);
      }
    }
  }

  return new ShapeFieldCacheDistanceValueSource(ctx, p, queryPoint);
}
 
Example 4
Source Project: Elasticsearch   Source File: GeoPointType.java    License: Apache License 2.0 5 votes vote down vote up
private static Double[] pointFromString(String value) {
    try {
        Point point = (Point)SPATIAL_CONTEXT.readShapeFromWkt(value);
        return new Double[] {point.getX(), point.getY()};
    } catch (ParseException e) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "Cannot convert \"%s\" to geo_point", value), e);
    }
}
 
Example 5
Source Project: Elasticsearch   Source File: GeoShapeFieldMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mapper parse(ParseContext context) throws IOException {
    try {
        Shape shape = context.parseExternalValue(Shape.class);
        if (shape == null) {
            ShapeBuilder shapeBuilder = ShapeBuilder.parse(context.parser(), this);
            if (shapeBuilder == null) {
                return null;
            }
            shape = shapeBuilder.build();
        }
        if (fieldType().pointsOnly() && !(shape instanceof Point)) {
            throw new MapperParsingException("[{" + fieldType().names().fullName() + "}] is configured for points only but a " +
                    ((shape instanceof JtsGeometry) ? ((JtsGeometry)shape).getGeom().getGeometryType() : shape.getClass()) + " was found");
        }
        Field[] fields = fieldType().defaultStrategy().createIndexableFields(shape);
        if (fields == null || fields.length == 0) {
            return null;
        }
        for (Field field : fields) {
            if (!customBoost()) {
                field.setBoost(fieldType().boost());
            }
            context.doc().add(field);
        }
    } catch (Exception e) {
        throw new MapperParsingException("failed to parse [" + fieldType().names().fullName() + "]", e);
    }
    return null;
}
 
Example 6
Source Project: Elasticsearch   Source File: MultiPointBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Shape build() {
    //Could wrap JtsGeometry but probably slower due to conversions to/from JTS in relate()
    //MultiPoint geometry = FACTORY.createMultiPoint(points.toArray(new Coordinate[points.size()]));
    List<Point> shapes = new ArrayList<>(points.size());
    for (Coordinate coord : points) {
        shapes.add(SPATIAL_CONTEXT.makePoint(coord.x, coord.y));
    }
    XShapeCollection multiPoints = new XShapeCollection<>(shapes, SPATIAL_CONTEXT);
    multiPoints.setPointsOnly(true);
    return multiPoints;
}
 
Example 7
Source Project: titan1withtp3.1   Source File: LuceneIndex.java    License: Apache License 2.0 5 votes vote down vote up
private String toWkt(Shape shape) {
    if(shape instanceof Point) {
        return "POINT(" + ((Point) shape).getX() + " " + ((Point) shape).getY() + ")";
    }
    else {
        throw new IllegalArgumentException("Only points are supported");
    }
}
 
Example 8
@Override
public void onRecordAddedToResultSet(QueryContext queryContext, OContextualRecordId recordId, Document doc, ScoreDoc score) {

  SpatialQueryContext spatialContext = (SpatialQueryContext) queryContext;
  if (spatialContext.spatialArgs != null) {
    Point docPoint = (Point) ctx.readShape(doc.get(strategy.getFieldName()));
    double docDistDEG = ctx.getDistCalc().distance(spatialContext.spatialArgs.getShape().getCenter(), docPoint);
    final double docDistInKM = DistanceUtils.degrees2Dist(docDistDEG, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM);
    recordId.setContext(new HashMap<String, Object>() {
      {
        put("distance", docDistInKM);
      }
    });
  }
}
 
Example 9
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 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
@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 12
@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 13
Source Project: Elasticsearch   Source File: PointBuilder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Point build() {
    return SPATIAL_CONTEXT.makePoint(coordinate.x, coordinate.y);
}
 
Example 14
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 15
Source Project: orientdb-lucene   Source File: OShapeFactoryImpl.java    License: Apache License 2.0 4 votes vote down vote up
protected OShapeFactoryImpl() {
  registerFactory(Point.class, new OPointShapeFactory());
  registerFactory(Rectangle.class, new ORectangleShapeFactory());
  registerFactory(Shape.class, new OPolygonShapeFactory());
}
 
Example 16
Source Project: incubator-retired-blur   Source File: ShapeReadWriter.java    License: Apache License 2.0 4 votes vote down vote up
/** Reads geospatial latitude then a comma then longitude. */
private Point readLatCommaLonPoint(String value) throws InvalidShapeException {
  double[] latLon = ParseUtils.parseLatitudeLongitude(value);
  return ctx.makePoint(latLon[1], latLon[0]);
}