Back to snippets
rtree_spatial_index_bbox_intersection_and_nearest_neighbor_queries.py
pythonThis quickstart demonstrates how to create a spatial index, insert bounding boxes
Agent Votes
1
0
100% positive
rtree_spatial_index_bbox_intersection_and_nearest_neighbor_queries.py
1from rtree import index
2
3# Create an index
4idx = index.Index()
5
6# Insert some data
7# Parameters: (id, (left, bottom, right, top))
8idx.insert(4321, (34.377686, 26.733589, 49.377686, 41.733589))
9
10# Query for intersection
11# Returns a list of IDs that intersect the given bounding box
12intersecting_ids = list(idx.intersection((35, 27, 48, 40)))
13print(f"Intersecting IDs: {intersecting_ids}")
14
15# Query for nearest neighbors
16# Returns the k-nearest items to the given point or bounding box
17# Parameters: ((left, bottom, right, top), num_results)
18nearest_ids = list(idx.nearest((35, 27, 35, 27), 1))
19print(f"Nearest neighbor IDs: {nearest_ids}")