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

The following examples show how to use com.spatial4j.core.shape.Shape. 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
Source Project: Elasticsearch   Source File: GeoJSONUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> shape2Map(Shape shape) {
    if (shape instanceof ShapeCollection) {
        ShapeCollection<?> shapeCollection = (ShapeCollection<?>)shape;
        List<Map<String, Object>> geometries = new ArrayList<>(shapeCollection.size());
        for(Shape collShape : shapeCollection) {
            geometries.add(shape2Map(collShape));
        }
        return ImmutableMap.of(
                TYPE_FIELD, GEOMETRY_COLLECTION,
                GEOMETRIES_FIELD, geometries
                );
    } else {
        try {
            return GEOJSON_CONVERTER.convert(JtsSpatialContext.GEO.getGeometryFrom(shape));
        } catch (InvalidShapeException e) {
            throw new IllegalArgumentException(
                    String.format(Locale.ENGLISH, "Cannot convert shape %s to Map", shape), e);
        }
    }
}
 
Example 2
Source Project: Elasticsearch   Source File: BaseLineStringBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Shape build() {
    Coordinate[] coordinates = points.toArray(new Coordinate[points.size()]);
    Geometry geometry;
    if(wrapdateline) {
        ArrayList<LineString> strings = decompose(FACTORY, coordinates, new ArrayList<LineString>());

        if(strings.size() == 1) {
            geometry = strings.get(0);
        } else {
            LineString[] linestrings = strings.toArray(new LineString[strings.size()]);
            geometry = FACTORY.createMultiLineString(linestrings);
        }

    } else {
        geometry = FACTORY.createLineString(coordinates);
    }
    return jtsGeometry(geometry);
}
 
Example 3
private Document newGeoDocument(OIdentifiable oIdentifiable, Shape shape) {

    FieldType ft = new FieldType();
    ft.setIndexed(true);
    ft.setStored(true);

    Document doc = new Document();

    doc.add(OLuceneIndexType.createField(RID, oIdentifiable.getIdentity().toString(), Field.Store.YES,
        Field.Index.NOT_ANALYZED_NO_NORMS));
    for (IndexableField f : strategy.createIndexableFields(shape)) {
      doc.add(f);
    }

    doc.add(new StoredField(strategy.getFieldName(), ctx.toString(shape)));

    return doc;
  }
 
Example 4
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 5
@Override
public Filter makeFilter(SpatialArgs args) {
  final SpatialOperation op = args.getOperation();
  if (op != SpatialOperation.Intersects)
    throw new UnsupportedSpatialOperation(op);

  Shape shape = args.getShape();
  int detailLevel = grid.getLevelForDistance(args.resolveDistErr(ctx, distErrPct));
  List<Cell> cells = grid.getCells(shape, detailLevel, false,// no parents
      true);// simplify
  BytesRef[] terms = new BytesRef[cells.size()];
  int i = 0;
  for (Cell cell : cells) {
    terms[i++] = new BytesRef(cell.getTokenString());
  }
  return new TermsFilter(getFieldName(), terms);
}
 
Example 6
@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 7
@Override
public Iterable<? extends Field> getFieldsForColumn(String family, Column column) {
  synchronized (_strategy) {
    String name = getName(family, column.getName());
    if (!_strategy.getFieldName().equals(name)) {
      throw new RuntimeException("Strategy name and column name do not match.");
    }
    List<Field> fields = new ArrayList<Field>();
    Shape shape = getShape(column);
    checkShape(shape);
    for (Field f : _strategy.createIndexableFields(shape)) {
      fields.add(f);
    }
    fields.add(new StoredField(name, column.getValue()));
    return fields;
  }
}
 
Example 8
@Override
public Iterable<? extends Field> getFieldsForSubColumn(String family, Column column, String subName) {
  synchronized (_strategy) {
    String name = getName(family, column.getName(), subName);
    if (!_strategy.getFieldName().equals(name)) {
      throw new RuntimeException("Strategy name and column name do not match.");
    }
    List<Field> fields = new ArrayList<Field>();
    Shape shape = getShape(column);
    checkShape(shape);
    for (Field f : _strategy.createIndexableFields(shape)) {
      fields.add(f);
    }
    return fields;
  }
}
 
Example 9
Source Project: Elasticsearch   Source File: GeoJSONUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Shape wkt2Shape(String wkt) {
    try {
        return JtsSpatialContext.GEO.readShapeFromWkt(wkt);
    } catch (Throwable e) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "Cannot convert WKT \"%s\" to shape", wkt), e);
    }
}
 
Example 10
Source Project: Elasticsearch   Source File: GeoJSONUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Shape map2Shape(Map<String, Object> geoJSONMap) {
    try {
        return geoJSONString2Shape(XContentFactory.jsonBuilder().map(geoJSONMap).string());
    } catch (Throwable e) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "Cannot convert Map \"%s\" to shape", geoJSONMap), e);
    }
}
 
Example 11
Source Project: Elasticsearch   Source File: GeoJSONUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Shape geoJSONString2Shape(String geoJSON) {
    try {
        XContentParser parser = JsonXContent.jsonXContent.createParser(geoJSON);
        parser.nextToken();
        return ShapeBuilder.parse(parser).build();
    } catch (Throwable t) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "Cannot convert GeoJSON \"%s\" to shape", geoJSON), t);
    }
}
 
Example 12
Source Project: Elasticsearch   Source File: GeoShapeType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int compareValueTo(Map<String, Object> val1, Map<String, Object> val2) {
    // TODO: compare without converting to shape
    Shape shape1 = GeoJSONUtils.map2Shape(val1);
    Shape shape2 = GeoJSONUtils.map2Shape(val2);
    switch (shape1.relate(shape2)) {
        case WITHIN:
            return -1;
        case CONTAINS:
            return 1;
        default:
            return Double.compare(shape1.getArea(JtsSpatialContext.GEO), shape2.getArea(JtsSpatialContext.GEO));
    }
}
 
Example 13
Source Project: Elasticsearch   Source File: LuceneQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private SpatialArgs getArgs(Shape shape, ShapeRelation relation) {
    switch (relation) {
        case INTERSECTS:
            return new SpatialArgs(SpatialOperation.Intersects, shape);
        case DISJOINT:
            return new SpatialArgs(SpatialOperation.IsDisjointTo, shape);
        case WITHIN:
            return new SpatialArgs(SpatialOperation.IsWithin, shape);
    }
    throw invalidMatchType(relation.getRelationName());
}
 
Example 14
Source Project: Elasticsearch   Source File: LuceneQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private Query getQuery(Function inner, Context context) {
    RefLiteralPair innerPair = new RefLiteralPair(inner);
    if (!innerPair.isValid()) {
        return null;
    }
    if (innerPair.reference().valueType().equals(DataTypes.GEO_SHAPE)) {
        // we have within('POINT(0 0)', shape_column)
        return genericFunctionFilter(inner, context);
    }
    GeoPointFieldMapper.GeoPointFieldType geoPointFieldType = getGeoPointFieldType(
            innerPair.reference().ident().columnIdent().fqn(),
            context.mapperService);

    Map<String, Object> geoJSON = (Map<String, Object>) innerPair.input().value();
    Shape shape = GeoJSONUtils.map2Shape(geoJSON);
    Geometry geometry = JtsSpatialContext.GEO.getGeometryFrom(shape);
    IndexGeoPointFieldData fieldData = context.fieldDataService.getForField(geoPointFieldType);
    if (geometry.isRectangle()) {
        Rectangle boundingBox = shape.getBoundingBox();
        return new InMemoryGeoBoundingBoxQuery(
                new GeoPoint(boundingBox.getMaxY(), boundingBox.getMinX()),
                new GeoPoint(boundingBox.getMinY(), boundingBox.getMaxX()),
                fieldData
        );
    } else {
        Coordinate[] coordinates = geometry.getCoordinates();
        GeoPoint[] points = new GeoPoint[coordinates.length];
        for (int i = 0; i < coordinates.length; i++) {
            Coordinate coordinate = coordinates[i];
            points[i] = new GeoPoint(coordinate.y, coordinate.x);
        }
        return new GeoPolygonQuery(fieldData, points);
    }
}
 
Example 15
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 16
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 17
Source Project: Elasticsearch   Source File: GeometryCollectionBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Shape build() {

    List<Shape> shapes = new ArrayList<>(this.shapes.size());
    
    for (ShapeBuilder shape : this.shapes) {
        shapes.add(shape.build());
    }
        
    if (shapes.size() == 1)
        return shapes.get(0);
    else
        return new XShapeCollection<>(shapes, SPATIAL_CONTEXT);
    //note: ShapeCollection is probably faster than a Multi* geom.
}
 
Example 18
Source Project: titan1withtp3.1   Source File: LuceneIndex.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void restore(Map<String, Map<String, List<IndexEntry>>> documents, KeyInformation.IndexRetriever informations, BaseTransaction tx) throws BackendException {
    writerLock.lock();
    try {
        for (Map.Entry<String, Map<String, List<IndexEntry>>> stores : documents.entrySet()) {
            String store = stores.getKey();
            IndexWriter writer = getWriter(store);
            IndexReader reader = DirectoryReader.open(writer, true);
            IndexSearcher searcher = new IndexSearcher(reader);

            for (Map.Entry<String, List<IndexEntry>> entry : stores.getValue().entrySet()) {
                String docID = entry.getKey();
                List<IndexEntry> content = entry.getValue();

                if (content == null || content.isEmpty()) {
                    if (log.isTraceEnabled())
                        log.trace("Deleting document [{}]", docID);

                    writer.deleteDocuments(new Term(DOCID, docID));
                    continue;
                }

                Pair<Document, Map<String, Shape>> docAndGeo = retrieveOrCreate(docID, searcher);
                addToDocument(store, docID, docAndGeo.getKey(), content, docAndGeo.getValue(), informations);

                //write the old document to the index with the modifications
                writer.updateDocument(new Term(DOCID, docID), docAndGeo.getKey());
            }
            writer.commit();
        }
        tx.commit();
    } catch (IOException e) {
        throw new TemporaryBackendException("Could not update Lucene index", e);
    } finally {
        writerLock.unlock();
    }
}
 
Example 19
Source Project: titan1withtp3.1   Source File: LuceneIndex.java    License: Apache License 2.0 5 votes vote down vote up
private Pair<Document, Map<String, Shape>> retrieveOrCreate(String docID, IndexSearcher searcher) throws IOException {
    Document doc;
    TopDocs hits = searcher.search(new TermQuery(new Term(DOCID, docID)), 10);
    Map<String, Shape> geofields = Maps.newHashMap();

    if (hits.scoreDocs.length > 1)
        throw new IllegalArgumentException("More than one document found for document id: " + docID);

    if (hits.scoreDocs.length == 0) {
        if (log.isTraceEnabled())
            log.trace("Creating new document for [{}]", docID);

        doc = new Document();
        doc.add(new StringField(DOCID, docID, Field.Store.YES));
    } else {
        if (log.isTraceEnabled())
            log.trace("Updating existing document for [{}]", docID);

        int docId = hits.scoreDocs[0].doc;
        //retrieve the old document
        doc = searcher.doc(docId);
        for (IndexableField field : doc.getFields()) {
            if (field.stringValue().startsWith(GEOID)) {
                try {
                    geofields.put(field.name(), ctx.readShapeFromWkt(field.stringValue().substring(GEOID.length())));
                } catch (java.text.ParseException e) {
                    throw new IllegalArgumentException("Geoshape was unparsable");
                }
            }
        }
    }

    return new ImmutablePair<Document, Map<String, Shape>>(doc, geofields);
}
 
Example 20
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 21
Source Project: titan1withtp3.1   Source File: Geoshape.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts this shape into its equivalent Spatial4j {@link Shape}.
 * @return
 */
public Shape convert2Spatial4j() {
    switch(getType()) {
        case POINT: return getPoint().getSpatial4jPoint();
        case CIRCLE: return CTX.makeCircle(getPoint(0).getSpatial4jPoint(), DistanceUtils.dist2Degrees(getRadius(), DistanceUtils.EARTH_MEAN_RADIUS_KM));
        case BOX: return CTX.makeRectangle(getPoint(0).getSpatial4jPoint(),getPoint(1).getSpatial4jPoint());
        case POLYGON: throw new UnsupportedOperationException("Not yet supported");
        default: throw new IllegalStateException("Unrecognized type: " + getType());
    }
}
 
Example 22
Source Project: rya   Source File: SpatialSupportInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean sfCrosses(Shape s1, Shape s2) {
    Geometry g1 = context.getGeometryFrom(s1);
    Geometry g2 = context.getGeometryFrom(s2);
    int d1 = g1.getDimension();
    int d2 = g2.getDimension();
    if ((d1 == 0 && d2 == 1) || (d1 == 0 && d2 == 2) || (d1 == 1 && d2 == 2)) {
        return g1.relate(g2, "T*T***T**");
    } else if (d1 == 1 && d2 == 1) {
        return g1.relate(g2, "0*T***T**");
    } else {
        return false;
    }
}
 
Example 23
Source Project: rya   Source File: SpatialSupportInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean sfOverlaps(Shape s1, Shape s2) {
    Geometry g1 = context.getGeometryFrom(s1);
    Geometry g2 = context.getGeometryFrom(s2);
    int d1 = g1.getDimension();
    int d2 = g2.getDimension();
    if ((d1 == 2 && d2 == 2) || (d1 == 0 && d2 == 0)) {
        return g1.relate(g2, "T*T***T**");
    } else if (d1 == 1 && d2 == 1) {
        return g1.relate(g2, "1*T***T**");
    } else {
        return false;
    }
}
 
Example 24
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 25
public Object searchWithin(OSpatialCompositeKey key, OCommandContext context) throws IOException {

    Set<OIdentifiable> result = new HashSet<OIdentifiable>();

    Shape shape = factory.makeShape(key, ctx);
    if (shape == null)
      return null;
    SpatialArgs args = new SpatialArgs(SpatialOperation.IsWithin, shape);
    IndexSearcher searcher = getSearcher();

    Filter filter = strategy.makeFilter(args);

    return new LuceneResultSet(this, new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter));
  }
 
Example 26
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 27
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 28
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 29
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 30
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]);
}