com.spatial4j.core.shape.Shape Java Examples
The following examples show how to use
com.spatial4j.core.shape.Shape.
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: ShapeReadWriter.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
/** 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 #2
Source File: TermQueryPrefixTreeStrategy.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
@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 #3
Source File: OLuceneSpatialIndexManager.java From orientdb-lucene with Apache License 2.0 | 6 votes |
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 File: SpatialRecursivePrefixTreeStrategyFieldTypeDefinition.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
@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 #5
Source File: BaseSpatialFieldTypeDefinition.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
@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 #6
Source File: BaseSpatialFieldTypeDefinition.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
@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 #7
Source File: BaseLineStringBuilder.java From Elasticsearch with Apache License 2.0 | 6 votes |
@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 #8
Source File: GeoJSONUtils.java From Elasticsearch with Apache License 2.0 | 6 votes |
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 #9
Source File: GeometryCollectionBuilder.java From Elasticsearch with Apache License 2.0 | 5 votes |
@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 #10
Source File: GeoJSONUtils.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #11
Source File: SpatialArgsParser.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
/** * 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: GeoJSONUtils.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #13
Source File: MultiPointBuilder.java From Elasticsearch with Apache License 2.0 | 5 votes |
@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 #14
Source File: GeoShapeFieldMapper.java From Elasticsearch with Apache License 2.0 | 5 votes |
@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 #15
Source File: LuceneQueryBuilder.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #16
Source File: GeoShapeType.java From Elasticsearch with Apache License 2.0 | 5 votes |
@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 #17
Source File: BaseSpatialFieldTypeDefinition.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
protected void checkShape(Shape shape) { for (Class<? extends Shape> shapeType : _supportedIndexedShapes) { if (shapeType.isInstance(shape)) { return; } } throw new IllegalArgumentException(_strategy.getClass().getName() + " only supports [" + _supportedIndexedShapes + "] operation."); }
Example #18
Source File: RecursivePrefixTreeStrategy.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
@Override public Filter makeFilter(SpatialArgs args) { final SpatialOperation op = args.getOperation(); if (op == SpatialOperation.IsDisjointTo) return new DisjointSpatialFilter(this, args, getFieldName()); Shape shape = args.getShape(); int detailLevel = grid.getLevelForDistance(args.resolveDistErr(ctx, distErrPct)); final boolean hasIndexedLeaves = true; if (op == SpatialOperation.Intersects) { return new IntersectsPrefixTreeFilter(shape, getFieldName(), grid, detailLevel, prefixGridScanLevel, hasIndexedLeaves); } else if (op == SpatialOperation.IsWithin) { return new WithinPrefixTreeFilter(shape, getFieldName(), grid, detailLevel, prefixGridScanLevel, -1);// -1 // flag // is // slower // but // ensures // correct // results } else if (op == SpatialOperation.Contains) { return new ContainsPrefixTreeFilter(shape, getFieldName(), grid, detailLevel); } throw new UnsupportedSpatialOperation(op); }
Example #19
Source File: GeoJSONUtils.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #20
Source File: BlurIndex.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
private String getValue(Object value) { if (value instanceof Number) { return value.toString(); } else if (value instanceof String) { return (String) value; } else if (value instanceof Geoshape) { Shape shape = ((Geoshape) value).convert2Spatial4j(); return shape.toString(); } throw new IllegalArgumentException("Unsupported type: " + value); }
Example #21
Source File: OPolygonShapeFactory.java From orientdb-lucene with Apache License 2.0 | 5 votes |
@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 #22
Source File: SpatialSupportInitializer.java From rya with Apache License 2.0 | 5 votes |
@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 File: ORectangleShapeFactory.java From orientdb-lucene with Apache License 2.0 | 5 votes |
@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 #24
Source File: SpatialSupportInitializer.java From rya with Apache License 2.0 | 5 votes |
@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 #25
Source File: OShapeFactoryImpl.java From orientdb-lucene with Apache License 2.0 | 5 votes |
@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 #26
Source File: OPointShapeFactory.java From orientdb-lucene with Apache License 2.0 | 5 votes |
@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 #27
Source File: OLuceneWithinOperator.java From orientdb-lucene with Apache License 2.0 | 5 votes |
@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 File: OLuceneNearOperator.java From orientdb-lucene with Apache License 2.0 | 5 votes |
@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 #29
Source File: OLuceneSpatialIndexManager.java From orientdb-lucene with Apache License 2.0 | 5 votes |
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 #30
Source File: GeoCircle.java From stratio-cassandra with Apache License 2.0 | 5 votes |
/** * {@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); }