-2

How can I create an r-tree index in memory, using Geodjango?

I have a number of fixed polygons (hardcoded) and I would like to check in which of these polygons does a point belong.

I would like to do this in memory to avoid being dependent on a spatial database.

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
Helgi Borg
  • 835
  • 10
  • 32

1 Answers1

0

What you can use is a library named: Rtree which is independent of a spatially enabled database.

From the tutorial:

# Import the library and create an index:
from rtree import index
idx = index.Index()

# Insert your fixed polygons to the index by the envelope (bounding box)
# coordinates of those polygons:
for index, polygon in enumerate(my_polygon_list):
    idx.insert(index, polygon.envelope)

# To query with a point you can do the following (explanation after the example):
potential_polys = list(idx.intersection((point.x, point.y, point.x, point.y)))

Break it up:

  • The part of the tutorial on how to set up a Rtree index is pretty simple.
  • A Geometry's bounding box (or envelope) coordinates must have the following format:
    (xmin, ymin, xmax, ymax) or (left, bottom, right, top).
  • On the documentation is stated that:

    Inserting a point, i.e. where left == right && top == bottom, will essentially insert a single point entry into the index instead of copying extra coordinates and inserting them. There is no shortcut to explicitly insert a single point, however.

    So we are using this "quirk" to apply our point to polygon intersection query on the index.

John Moutafis
  • 22,254
  • 11
  • 68
  • 112