geocoding and spatial database queries using python with django and postgis

No Gravatar

Python is an excellent language for developing GIS applications.  It’s very easy to create a web service that postgisqueries a spatial database and returns a result.  Sometimes that sort of thing is called a location based service.  They are common in mobile applications, including iphone apps.  For our purposes, latitude and longitude are just inputs to a function.

Geocoding is the act of turning street addresses into coordinates on a map.  A geocoding service takes an address or a more generic reference to streets and returns a latitude and longitude that can be plotted on a map.  Reverse geocoding takes a point and returns an address, but we won’t be going into that here.

Google provides an excellent geocoding service that has a flexible address matching algorithm and provides  accurate results.  It can be used in python by way of the geopy module.  The module can also query other geocoding services like yahoo and microsoft, but google does a good job and works well with the Google Maps API and base layer.  The syntax to look up a location by the street address is simple.

This example also includes using that geocoded address to look up the Portland neighborhood in which the point is located.  To do this we must have a geodjango model loaded in a postgis or other spatial database or geodatabase as they are sometimes called.


from django.contrib.gis.geos import Point
from models import Neighborhood
from geopy import geocoders
api_key='AAJJDJDJSJ....'

g = geocoders.Google(api_key)
place, (lat, lon) = g.geocode(address)
pnt = Point(lon,lat)
n = Neighborhood.objects.get(poly__intersects=pnt)

About edwin

I'm a web developer living in a post gis world. I’m interested in open source software, open data, GIS, spatial databases (geodatabases), web mapping applications and location based services. I love javascript (node!), python and postgresql.
This entry was posted in technology and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>