Search Nearby using Rtree
Searching POIs nearby to user location or any location feature in LBS service is critical component (in fact everyone knows that, nothing new). But exciting is rtree library in python. Well here is small example code using python rtree library that uses internally libspatialindex.
Here is a sampel code how rtree can be utilized to index all of your POIs
from rtree import index
# locations=array of {id:1,coordinate:(x1,y1),name:"htel abc"}
def create_index(locations,index_name):
idx=index.Index(index_name)
for location in locations:
id = location['id']
x = location['coordinate'][0]
y = location['coordinate'][1]
idx.insert(id,(x,y))
del idx
In this sample a function create_index just loop through all of POIs and create a rtree index. It creates index files with index_name (index_name.idx and index_name.dat). So when you want to search the nearby location you load index with these files. The next sample code shows how easily one can find the near locations.
# returns list of ids
#coordinate - (x1,y1), count - no of ids to be returned
def find_nearby(coordinate,count,index_name):
idx = index.Index(index_name)
x = coordinate[0]
y = coordinate[1]
return idx.nearest((x,y),count)
So keep indexing your locations and find nearby very easily.
