Spatial4j Documentation

repository·master·Indexed 21 days ago

https://github.com/locationtech/spatial4j

A Java library for geospatial operations providing shape modeling, spatial math, and data I/O. It supports Euclidean and geodesic models for shapes like Point, Rectangle, Circle, LineString, and Polygon. The library includes distance calculations (Law of Cosines, Haversine, Vincenty) and supports WKT, GeoJSON, and Polyshape formats. It requires Java 8+ and offers optional integration with JTS, Noggit, and Jackson-databind.

Tokens
1.6K
Snippets
1
Records
9
Agent score
26%

What's inside Spatial4j

  1. Understand the core capabilities of Spatial4j

    master

    Spatial4j is a general-purpose geospatial Java library designed for three primary tasks:

    1. Shape Modeling: Provides common shapes (Point, Rectangle, Circle, LineString, Polygon, etc.) that work in both Euclidean (flat 2D) and geodesic (surface-of-a-sphere) world models.
    2. Spatial Math: Provides distance calculations (including great-circle distances) and other geometric math.
    3. Data I/O: Reads and writes shapes using formats like WKT (Well-Known Text), GeoJSON, and Polyshape.

    It is particularly useful when working with spatial grid-square indexing schemes like Geohash.

  2. Compare Spatial4j shape support across models

    master

    Spatial4j shapes support different mathematical models. Use the following table to determine which shapes are available for your specific use case:

    ShapeEuclidean (Flat)Cylindrical (Wrap X)Spherical (Geodesic)
    PointYYY
    RectangleYYY
    CircleYNY
    LineStringYNN
    Buffered L/SYNN
    PolygonYYN
    ShapeCollectionYYY

    Key Notes:

    • Rectangle in the spherical model is treated as a lat-lon rectangle (cylindrical math).
    • Polygons support dateline-crossing (wrap-around at -180/+180) but do not support pole-wrap (Antarctica). Polygons are implemented by wrapping JTS Geometry.
  3. Identify Spatial4j dependencies and requirements

    master

    Spatial4j requires Java 8 (v1.8) or better.

    Some features require optional dependencies:

    • JTS: Required if you use Polygons or any classes prefixed with Jts.
    • Noggit: Required for parsing GeoJSON (writing GeoJSON does not require this).
    • Jackson-databind: Required if you want to use Spatial4j's Jackson-databind integration for reading/writing shapes.
  4. Configure and initialize Spatial4j using SpatialContext

    master

    The SpatialContext is the primary facade for the library. It acts as a factory for shapes and provides convenience methods for distance calculations.

    Best Practice: Avoid calling constructors for most Spatial4j classes directly. Instead, use SpatialContextFactory or the provided singletons to ensure proper abstraction and extension points.

    Ways to get a SpatialContext:

    1. Use Global Singletons (Quickest for standard use):

      • SpatialContext.GEO: Uses geodesic surface-of-sphere calculations.
      • JtsSpatialContext.GEO: Uses geodesic calculations and adds Polygon support via JTS.
    2. Custom Configuration via Factory: Instantiate a SpatialContextFactory (or JtsSpatialContextFactory), set your desired options, and then call newSpatialContext().

    3. Configuration from Properties: If you have name-value pairs (e.g., from a .properties file), use the static method SpatialContext.makeSpatialContext(map, classLoader) for flexible initialization.

  5. Use the Reader/Writer API to encode and decode shapes

    master

    Spatial4j provides ShapeReader and ShapeWriter interfaces to convert between Shape objects and string representations. You can obtain these from a SpatialContext instance using the getFormats() method and specifying the desired format via ShapeIO constants.

    Note: Reading and writing polygons specifically requires a reader/writer obtained from a JtsSpatialContext.

    SpatialContext ctx = ...;
    ShapeReader shpReader = ctx.getFormats().getReader(ShapeIO.WKT);
    ShapeWriter shpWriter = ctx.getFormats().getWriter(ShapeIO.WKT);
  6. Well Known Text (WKT) format reference

    master

    Well-Known-Text (WKT) is a text-based format defined by the OGC Simple Feature Specification. Spatial4j includes extensions like BUFFER and ENVELOPE (borrowed from CQL).

    Supported WKT Mappings:

    ShapeWKT Syntax
    PointPOINT(1 2)
    RectangleENVELOPE(minX, maxX, maxY, minY)
    CircleBUFFER(POINT(-10 30), 5.2)
    LineStringLINESTRING(1 2, 3 4)
    Buffered L/SBUFFER(LINESTRING(1 2, 3 4), 0.5)
    PolygonPOLYGON ((1 1, 2 1, 2 2, 1 2, 1 1))
    ShapeCollectionGEOMETRYCOLLECTION(POINT(1 2),LINESTRING(1 2, 3 4))

    Note: In BUFFER(shape, distance), the distance is in degrees. For ENVELOPE, the argument order is minX, maxX, maxY, minY.

  7. Polyshape format reference

    master

    Polyshape is a compact ASCII format extending Google's Polyline algorithm. It uses a prefix key to denote shape types and supports optional arguments inside parentheses () for properties like radius or buffer size.

    Prefix Keys:

    ShapeKey
    Point0
    LineString1
    Polygon2
    MultiPoint3
    Circle4
    Rectangle5

    Key Features:

    • Collections: Represented by concatenating individual shape encodings with a space (e.g., 0_abc 1_def).
    • Polygons with Holes: Represented by appending the encoding of each interior ring prefixed with a ')'. Format: '2' + encode(exteriorRing) + ['(' + encode(interiorRing)]*.
    • Arguments: If a '(' follows the prefix, everything until the next ')' is treated as an argument (e.g., for Circle radius or LineString buffer).

    Limitations:

    • Optimized for lat/lon; very large/small values may be lost due to rounding to Math.round(value * 1e5).
    • In the JTS version, homogeneous ShapeCollections may be read as MultiPoint, MultiLineString, or MultiPolygon.
  8. Reference supported spatial formats and math

    master

    Spatial4j supports several data formats and distance calculation algorithms:

    Supported Formats

    • WKT (Well-Known Text): Includes the ENVELOPE extension from CQL and a custom BUFFER operation (buffering a point produces a Circle).
    • GeoJSON
    • Polyshape
    • Jackson-databind serialization

    Distance Calculators

    Spatial4j provides three great-circle distance calculators:

    • Law of Cosines
    • Haversine
    • Vincenty
  9. GeoJSON format reference

    master

    GeoJSON is an open standard for representing geographic objects using JSON. Spatial4j supports the following structures:

    • Point: {"type": "Point", "coordinates": [1, 2]}
    • Rectangle: {"type": "Polygon", "coordinates": [[[1,3], [1,4], [2,4], [2,3], [1,3]]]}
    • Circle: {"type": "Circle", "coordinates": [1, 2], "radius": 111.19508, "properties": {"radius_units": "km"}}
    • LineString: {"type": "LineString", "coordinates": [[1, 2], [3, 4]]}
    • Buffered LineString: {"type": "LineString", "coordinates": [[1, 2], [3, 4]], "buffer": 10}
    • Polygon: {"type": "Polygon", "coordinates": [[[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]]}
    • ShapeCollection: {"type": "GeometryCollection", "geometries": [...]}