R-Tree Spatial Index for Python GIS

1.4.1 · active · verified Thu Apr 09

Rtree is a Python library that provides an R-Tree spatial index, implemented as a ctypes wrapper around the high-performance libspatialindex C library. It enables efficient spatial querying capabilities such as nearest neighbor and intersection searches for multi-dimensional data. The library supports bulk loading, deletion, and disk serialization of indexes, making it a crucial tool for various GIS and geospatial data processing tasks. It is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an in-memory R-tree index, insert spatial objects (represented by bounding boxes and optional associated data), and perform intersection and nearest-neighbor queries.

from rtree import index

# Create an in-memory R-tree index
idx = index.Index()

# Insert some bounding boxes (id, (minx, miny, maxx, maxy))
# Note: IDs are not enforced to be unique by Rtree itself
idx.insert(0, (0, 0, 1, 1)) # Item with ID 0, bounds (0,0) to (1,1)
idx.insert(1, (0.5, 0.5, 1.5, 1.5))
idx.insert(2, (2, 2, 3, 3))
idx.insert(3, (0.8, 0.8, 1.2, 1.2), obj={'name': 'Intersection Point'})

# Query for intersections with a given bounding box
search_bounds = (0.7, 0.7, 1.1, 1.1)
hits = list(idx.intersection(search_bounds))
print(f"IDs intersecting {search_bounds}: {hits}")

# Query for intersections and retrieve objects (if stored)
hits_with_objects = list(idx.intersection(search_bounds, objects=True))
print("Items intersecting (with objects):")
for item in hits_with_objects:
    print(f"  ID: {item.id}, Bounds: {item.bbox}, Object: {item.object}")

# Query for nearest neighbors
nearest_point = (0.1, 0.1)
nearest_items = list(idx.nearest(nearest_point, num_results=1))
print(f"Nearest item to {nearest_point}: {nearest_items}")

view raw JSON →