Using Prepared Geometries in Shapely

Shapely is a great tool for the geospatial developer.

With Shapely it is possible to run PostGIS-like operations on non-PostGIS geometries. This can keep your python code looking smooth and consistent. In my experience it can also go rocket fast in certain applications. One of those applications is where you are using the same geometry over and over for an operation.

A simple use case here might be geofencing, where you want to use the same geofence (polygon) over and over for a point-in-polygon analysis. Yes, geofencing is a fancy term for seeing is a point resides within a polygon or not.

In this case you would want to change one geometry (the point) and see if its inside or outside of a fixed geometry (the polygon). Shapely has an awesome way to speed up this process by using a prepared geometry.

Another use case is to see if one line is approximately following another, one vertex at a time. So, say you have a loop like this in django:

#where c is a django line geometry

#and r is also a django line geometry

#buffer distance is the buffer we will use to describe the polygon we will build

from django.contrib.gis.geos import Point

c_buffer = c.buffer(buffer_distance)

for coord in r:

coord_point = Point(coord)

if coord_point.within(c_buffer):

print “sweet we are in the buffer”

else:

print “unlucky, outside the buffer”

The shapely version will look like this:

from shapely.geometry import Point as ShapelyPoint

from shapely.geometry import LineString as ShapelyLinestring

from shapely.prepared import prep

#import the shapely libraries (you will have had to pip install them already of course!)

c_linestring = ShapelyLinestring(c)

#yup, we have to convert the linestring into a shapely linestring

c_buffer = prep(c_linestring.buffer(buffer_distance))

#now all we do is add in the “prep” operation

for coord in r: coord_point = ShapelyPoint(coord)

#again, we must build a shapely geometry

if coord_point.within(c_buffer):

print “sweet we are in the buffer”

else:

print “unlucky, outside the buffer”

#the rest of the code is exactly the same!

As you can tell these two code snippets are not vastly different. There is some overhead is using the shapely library, but if you are going to be checking the contents of a buffer over 50 times continually (or so) it really is worth consideration.

Yay for Shapely!

Find out more about prepared geometries