Geocoding in web applications: OpenLayers and geoPy to the rescue!
17 September 2010
In many situations, in your web applications, you will need a feature for geocoding an address, a city, a country…
In this post I will show how to use geoPy, OpenLayers and a bit of jQuery to assemble a simple but nice tool for geocoding within OpenLayers.
In my server code I will use Django but you may opt for any Python web framework (Pylons, Zope, TurboGears, web2py…) with very slight modifications to the code.
Basically this is what the tool will do: typing an address or place in a jQuery dialog, the dialog will be filled with results from three major gecoding services (Google, Yahoo! and GeoNames). Each result will be a link, and clicking on it there will be a zoom at that place in the OpenLayers map.
The idea is to expose a Django view accepting a string parameter (the place name to geocode) giving an xml output like this one:
This is the Django view implementing this functionality:
Basically the geolocate view checks if in the request there is the address string to geocode, and then by using the minidom API it creates the output xml.
Note that each location node is built by querying the geocoding service with a geoPy’s geocoder object.
On the client side, there will be an html page with an OpenLayers map in it, and the jQuery dialog needed from the application.
This is an extract of it:
At this point, clicking on the search link, the dialog will open, linked to the map, and the Django view will be requested to get the necessary xml.
Basically, when the search-dialog opens and the user types a search string in the txtAddress input, the getLocations method is invoked.
This method will send an AJAX xml request to the Django view and, in case of success, will parse the xml Django response to compose the geolink list in the dialog.