org.locationtech.spatial4j.context.jts.JtsSpatialContext Java Examples

The following examples show how to use org.locationtech.spatial4j.context.jts.JtsSpatialContext. 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: GeoJSONUtils.java    From crate with 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 Map.of(
            TYPE_FIELD, GEOMETRY_COLLECTION,
            GEOMETRIES_FIELD, geometries
        );
    } else {
        try {
            return GEOJSON_CONVERTER.convert(JtsSpatialContext.GEO.getShapeFactory().getGeometryFrom(shape));
        } catch (InvalidShapeException e) {
            throw new IllegalArgumentException(
                String.format(Locale.ENGLISH, "Cannot convert shape %s to Map", shape), e);
        }
    }
}
 
Example #2
Source File: PointType.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
Point decodeUTF8Text(byte[] bytes) {
    String value = new String(bytes, StandardCharsets.UTF_8);
    StringTokenizer tokenizer = new StringTokenizer(value, ",()");
    double x;
    double y;
    if (tokenizer.hasMoreTokens()) {
        x = Double.parseDouble(tokenizer.nextToken());
    } else {
        throw new IllegalArgumentException("Cannot parse input as point: " + value + " expected a point in format: (x, y)");
    }
    if (tokenizer.hasMoreTokens()) {
        y = Double.parseDouble(tokenizer.nextToken());
    } else {
        throw new IllegalArgumentException("Cannot parse input as point: " + value + " expected a point in format: (x, y)");
    }
    return new PointImpl(x, y, JtsSpatialContext.GEO);
}
 
Example #3
Source File: GeoPointColumnReference.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public Point value() {
    try {
        if (values.advanceExact(docId)) {
            switch (values.docValueCount()) {
                case 1:
                    long encoded = values.nextValue();
                    return new PointImpl(
                        GeoEncodingUtils.decodeLongitude((int) encoded),
                        GeoEncodingUtils.decodeLatitude((int) (encoded >>> 32)),
                        JtsSpatialContext.GEO
                    );

                default:
                    throw new GroupByOnArrayUnsupportedException(columnName);
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #4
Source File: WithinQuery.java    From crate with Apache License 2.0 5 votes vote down vote up
private Query getQuery(Function inner, LuceneQueryBuilder.Context context) {
    RefAndLiteral innerPair = RefAndLiteral.of(inner);
    if (innerPair == null) {
        return null;
    }
    if (innerPair.reference().valueType().equals(DataTypes.GEO_SHAPE)) {
        // we have within('POINT(0 0)', shape_column)
        return LuceneQueryBuilder.genericFunctionFilter(inner, context);
    }
    GeoPointFieldMapper.GeoPointFieldType geoPointFieldType = getGeoPointFieldType(
        innerPair.reference().column().fqn(),
        context.mapperService);

    Map<String, Object> geoJSON = DataTypes.GEO_SHAPE.value(innerPair.literal().value());
    Geometry geometry;
    Shape shape = GeoJSONUtils.map2Shape(geoJSON);
    if (shape instanceof ShapeCollection) {
        int i = 0;
        ShapeCollection<Shape> collection = (ShapeCollection) shape;
        org.locationtech.jts.geom.Polygon[] polygons = new org.locationtech.jts.geom.Polygon[collection.size()];
        for (Shape s : collection.getShapes()) {
            Geometry subGeometry = JtsSpatialContext.GEO.getShapeFactory().getGeometryFrom(s);
            if (subGeometry instanceof org.locationtech.jts.geom.Polygon) {
                polygons[i++] = (org.locationtech.jts.geom.Polygon) subGeometry;
            } else {
                throw new InvalidShapeException("Shape collection must contain only Polygon shapes.");
            }
        }
        GeometryFactory geometryFactory = JtsSpatialContext.GEO.getShapeFactory().getGeometryFactory();
        geometry = geometryFactory.createMultiPolygon(polygons);
    } else {
        geometry = JtsSpatialContext.GEO.getShapeFactory().getGeometryFrom(shape);
    }

    return getPolygonQuery(geometry, geoPointFieldType);
}
 
Example #5
Source File: JavascriptUserDefinedFunctionTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testGeoTypeReturnTypeWithWKT() throws Exception {
    registerUserDefinedFunction(
        "f",
        DataTypes.GEO_POINT,
        List.of(),
        "function f() { return \"POINT (1.0 2.0)\"; }");
    assertEvaluate("f()", new PointImpl(1.0, 2.0, JtsSpatialContext.GEO));
}
 
Example #6
Source File: JavascriptUserDefinedFunctionTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testGeoTypeReturnTypeWithDoubleArray() throws Exception {
    registerUserDefinedFunction(
        "f",
        DataTypes.GEO_POINT,
        List.of(),
        "function f() { return [1, 1]; }");
    assertEvaluate("f()", new PointImpl(1.0, 1.0, JtsSpatialContext.GEO));
}
 
Example #7
Source File: InsertIntoIntegrationTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
@UseJdbc(0) // inserting geo-point array requires special treatment for PostgreSQL
public void testInsertIntoGeoPointArray() throws Exception {
    execute("create table t (id int, points array(geo_point)) clustered into 1 shards with (number_of_replicas=0)");
    ensureYellow();
    execute("insert into t (id, points) values (1, [[1.1, 2.2],[3.3, 4.4]])");
    execute("insert into t (id, points) values (2, ['POINT(5.5 6.6)','POINT(7.7 8.8)'])");
    execute("insert into t (id, points) values (?, ?)",
        new Object[]{3, new Double[][]{new Double[]{9.9, 10.10}, new Double[]{11.11, 12.12}}});
    execute("refresh table t");
    execute("select points from t order by id");
    assertThat(response.rowCount(), is(3L));
    assertThat(
        (List<Object>) response.rows()[0][0],
        contains(
            is(new PointImpl(1.1, 2.2, JtsSpatialContext.GEO)),
            is(new PointImpl(3.3, 4.4, JtsSpatialContext.GEO))
        )
    );
    assertThat(
        (List<Object>) response.rows()[1][0],
        contains(
            is(new PointImpl(5.5, 6.6, JtsSpatialContext.GEO)),
            is(new PointImpl(7.7, 8.8, JtsSpatialContext.GEO))
        )
    );
    assertThat(
        (List<Object>) response.rows()[2][0],
        contains(
            is(new PointImpl(9.9, 10.10, JtsSpatialContext.GEO)),
            is(new PointImpl(11.11, 12.12, JtsSpatialContext.GEO))
        )
    );
}
 
Example #8
Source File: GeoPointTypeTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreaming() throws Throwable {
    Point p1 = new PointImpl(41.2, -37.4, JtsSpatialContext.GEO);

    BytesStreamOutput out = new BytesStreamOutput();
    DataTypes.GEO_POINT.writeValueTo(out, p1);

    StreamInput in = out.bytes().streamInput();
    Point p2 = DataTypes.GEO_POINT.readValueFrom(in);

    assertThat(p1, equalTo(p2));
}
 
Example #9
Source File: GeoJSONUtilsTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testPoint2Map() throws Exception {
    Point point = GEOMETRY_FACTORY.createPoint(new Coordinate(0.0, 0.0));
    Shape shape = new JtsPoint(point, JtsSpatialContext.GEO);
    Map<String, Object> map = GeoJSONUtils.shape2Map(shape);
    assertThat(map, hasEntry("type", (Object) "Point"));
    assertThat(map.get("coordinates").getClass().isArray(), is(true));
    assertThat(((double[]) map.get("coordinates")).length, is(2));
}
 
Example #10
Source File: GeoShapeType.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(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 #11
Source File: GeoPointType.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Point readValueFrom(StreamInput in) throws IOException {
    if (in.readBoolean()) {
        return new PointImpl(in.readDouble(), in.readDouble(), JtsSpatialContext.GEO);
    } else {
        return null;
    }
}
 
Example #12
Source File: SpatialSupport.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected JtsSpatialContext createSpatialContext() {
	return JtsSpatialContext.GEO;
}
 
Example #13
Source File: PointType.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public Point readBinaryValue(ByteBuf buffer, int valueLength) {
    double x = buffer.readDouble();
    double y = buffer.readDouble();
    return new PointImpl(x, y, JtsSpatialContext.GEO);
}
 
Example #14
Source File: DistanceFunctionTest.java    From crate with Apache License 2.0 4 votes vote down vote up
@Test
public void testEvaluateWithTwoGeoPointLiterals() throws Exception {
    assertEvaluate("distance(geopoint, geopoint)", 144572.67952051832,
        Literal.of(DataTypes.GEO_POINT, new PointImpl(10.04, 28.02, JtsSpatialContext.GEO)),
        Literal.of(DataTypes.GEO_POINT, DataTypes.GEO_POINT.value("POINT(10.30 29.3)")));
}
 
Example #15
Source File: DataTypeTesting.java    From crate with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Supplier<T> getDataGenerator(DataType<T> type) {
    Random random = RandomizedContext.current().getRandom();
    switch (type.id()) {
        case ByteType.ID:
            return () -> (T) (Byte) (byte) random.nextInt(Byte.MAX_VALUE);
        case BooleanType.ID:
            return () -> (T) (Boolean) random.nextBoolean();

        case StringType.ID:
            return () -> (T) RandomizedTest.randomAsciiLettersOfLength(random.nextInt(10));

        case IpType.ID:
            return () -> {
                if (random.nextBoolean()) {
                    return (T) randomIPv4Address(random);
                } else {
                    return (T) randomIPv6Address(random);
                }
            };

        case DoubleType.ID:
            return () -> (T) (Double) random.nextDouble();

        case FloatType.ID:
            return () -> (T) (Float) random.nextFloat();

        case ShortType.ID:
            return () -> (T) (Short) (short) random.nextInt(Short.MAX_VALUE);

        case IntegerType.ID:
            return () -> (T) (Integer) random.nextInt();

        case LongType.ID:
        case TimestampType.ID_WITH_TZ:
        case TimestampType.ID_WITHOUT_TZ:
            return () -> (T) (Long) random.nextLong();

        case GeoPointType.ID:
            return () -> (T) new PointImpl(
                BiasedNumbers.randomDoubleBetween(random, -180, 180),
                BiasedNumbers.randomDoubleBetween(random, -90, 90),
                JtsSpatialContext.GEO
            );

        case GeoShapeType.ID:
            return () -> {
                // Can't use immutable Collections.singletonMap; insert-analyzer mutates the map
                Map<String, Object> geoShape = new HashMap<>(2);
                geoShape.put("coordinates", Arrays.asList(10.2d, 32.2d));
                geoShape.put("type", "Point");
                return (T) geoShape;
            };

        case ObjectType.ID:
            Supplier<?> innerValueGenerator = getDataGenerator(randomType());
            return () -> {
                // Can't use immutable Collections.singletonMap; insert-analyzer mutates the map
                HashMap<String, Object> map = new HashMap<>();
                map.put("x", innerValueGenerator.get());
                return (T) map;
            };
        case IntervalType.ID:
            return () -> {
                return (T) new Period().withSeconds(RandomNumbers.randomIntBetween(random, 0, Integer.MAX_VALUE));
            };

    }

    throw new AssertionError("No data generator for type " + type.getName());
}
 
Example #16
Source File: JtsSpatialAlgebra.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public JtsSpatialAlgebra(JtsSpatialContext context) {
	this.shapeFactory = context.getShapeFactory();
}
 
Example #17
Source File: SpatialSupport.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected JtsSpatialAlgebra createSpatialAlgebra() {
	return new JtsSpatialAlgebra((JtsSpatialContext) spatialContext);
}