Address geocoding with geopy
30 July 2012
Comments
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='maps.google.pl')
place, location = g.geocode(u"Warszawa, Marszałkowska 1".encode('utf-8'))
print place
print location
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='maps.google.pl')
_, start = g.geocode(u"Warszawa, Marszałkowska 1".encode('utf-8'))
_, finish = g.geocode(u"Szczecin".encode('utf-8'))
print distance.distance(start, finish)
RkBlog
Comment article