Skip to content
February 18, 2011 / Gagan

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):
	for location in locations:
		id = location['id']
		x = location['coordinate'][0]
		y = location['coordinate'][1]
	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.
Update: Here is a high performance JavaScript R-tree library RBush


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: