Address geocoding with geopy

geopy is handy module for address geocoding - turning a location address into geographic coordinates (useful for maps). It supports various geocoding engines like Google Maps, Yahoo!, Windows Local Live and others. This module can be used to aid your GeoDjango code.

The install is typical:
pip install geopy
And we can start using geopy. Geocoding looks like so:
# -*- coding: utf-8 -*-
from geopy import geocoders
g = geocoders.Google(domain='')

place, location = g.geocode(u"Warszawa, Marszałkowska 1".encode('utf-8'))

print place
print location
And the result:
Marszałkowska 1, 01-001 Warszawa, Polska
(52.2144351, 21.0208823)

As domain you may enter your local Google maps domain site to get better results. In my case it's the Polish version. geocode returns full address, latitude and longitude. Geographic location can be used now to put a marker on a Google Maps widget. If you want to store the location in the database you can use PointField from GeoDjango (if you use Django of course).

You can also estimate distance between two points:

# -*- coding: utf-8 -*-
from geopy import distance
from geopy import geocoders
g = geocoders.Google(domain='')

_, start = g.geocode(u"Warszawa, Marszałkowska 1".encode('utf-8'))
_, finish = g.geocode(u"Szczecin".encode('utf-8'))

print distance.distance(start, finish)
The result is 456.300972179 km. In case of GeoDjango applications distance operations are much bigger (you can query and order by distance). I'll write more about that in next article.


Python programming, 30 July 2012

Comment article
Comment article RkBlog main page Search RSS Contact