s2sphere
s2sphere is a Python implementation of a part of Google's C++ S2 Geometry Library. It provides tools for working with spherical geometry, such as mapping points and regions on a sphere to a 1D index, enabling scalable proximity searches on distributed indexes. The current version is 0.2.5, and it maintains an active release cadence, primarily via updates to its GitHub repository and PyPI package. [1, 2, 3]
Common errors
-
AttributeError: 'str' object has no attribute 'get_center'
cause Users often obtain S2 Cell IDs as hex-encoded string 'tokens' (e.g., from databases or APIs). Attempting to directly use `Cell` or `CellId` object methods like `get_center()` or `get_vertex()` on such a string will result in an `AttributeError` because these methods belong to `s2sphere.CellId` or `s2sphere.Cell` objects, not strings. [17]fixBefore using `CellId` or `Cell` methods, convert the hex-encoded string token into an `s2sphere.CellId` object using `s2sphere.CellId.from_token('your_hex_token_string')`. -
TypeError: argument of type 'int' is not iterable
cause Some S2 sphere functions, particularly those dealing with collections of CellIds (like a RegionCoverer's output), expect iterable inputs or return lists of `CellId` objects. Trying to pass a single integer or non-iterable where a collection is expected, or conversely, attempting to iterate over a single `CellId`'s internal 'id' attribute (which is an integer) will raise this error.fixEnsure that inputs to `s2sphere` functions match the expected type (e.g., lists of `CellId` objects, `LatLonRect` objects). If you have a single `CellId` and a function expects an iterable, wrap it in a list `[my_cell_id]`. Remember that `CellId` objects have an `id` attribute which is an integer, and the `CellId` object itself is what is typically passed around.
Warnings
- breaking The underlying C++ S2 Geometry Library, which `s2sphere` partially implements or binds to, explicitly states that its Python API is unstable and may be replaced. Future versions could introduce breaking changes due to a planned migration from SWIG to pybind11 for more Pythonic names and complete functionality. [5]
- gotcha The `s2sphere.CellId.walk_hilbert_curve` method internally mutates a single `CellId` instance to yield subsequent IDs. If you store or save the `CellId` object returned by the iterator directly, its value will change out from underneath you in subsequent iterations. [12]
- gotcha The `s2sphere` library is designed for spherical geometry. Applying assumptions from planar Euclidean geometry (e.g., straight-line distance, simple bounding boxes) can lead to incorrect results, especially over large distances or near poles. [3, 5, 9, 10]
Install
-
pip install s2sphere
Imports
- s2sphere
import s2sphere
- LatLon
from s2sphere.sphere import LatLon
s2sphere.LatLon.from_degrees(latitude, longitude)
Quickstart
import s2sphere
# Define two points using latitude and longitude
p1 = s2sphere.LatLon.from_degrees(33, -122)
p2 = s2sphere.LatLon.from_degrees(33.1, -122.1)
# Create a region coverer
r = s2sphere.RegionCoverer()
# Get the S2 cells covering a LatLon rectangle defined by the two points
cell_ids = r.get_covering(s2sphere.LatLonRect.from_point_pair(p1, p2))
# Print the resulting cell IDs
print(f"S2 Cell IDs covering the region: {cell_ids}")
# Example: Convert a CellId to LatLon
if cell_ids:
first_cell_id = cell_ids[0]
center_latlon = s2sphere.LatLng.from_point(s2sphere.Cell(first_cell_id).get_center())
print(f"Center of the first cell ({first_cell_id.to_token()}): {center_latlon.degrees()}, {center_latlon.lngdegrees()}")