Trouble of the day: Python, Geopy and GeoNames

Hi all!
Currently I'm working on the coolest thing I've ever done in my life.
I'll tell you more when it is almost over. I just tell you that after my professor proposed me to do this project as exam I was so excited that I needed almost four hour to calm down and answer his mail without sounding like a crazy little girl in a candy shop!


By the way, let's talk about my trouble of the day: we're working in Python, given a string token, I need to verify that it represents a place, and retrieve its coordinates (longitude and latitude). Notice that I don't know if it is a city, a state, a region, or just a zone.

So I needed to query a database like Geonames from my code. I used Geopy. I followed the instructions for installing and then copied&pasted the example for GeoNames on the website in my code, and I found out that.. it doesn't work!


 In fact, if you insert this code:

>>> from geopy import geocoders  
>>> gn = geocoders.GeoNames()  >>> place, (lat, lng) = gn.geocode("Cleveland, OH 44106")  >>> print "%s: %.5f, %.5f" % (place, lat, lng) 


It raises: "geopy.exc.ConfigurationError: No username given, required for api access.  If you do not have a GeoNames username, sign up here: http://www.geonames.org/login"

For fixing this I just had to:

- Register on GeoNames
- Enable the webservice privileges for my account (going to manage account
- Modify my code like that:

>>> from geopy import geocoders  
>>> gn = geocoders.GeoNames(username="myusername")   
>>> place, (lat, lng) = gn.geocode("Cleveland, OH 44106")  
 >>> print "%s: %.5f, %.5f" % (place, lat, lng) 
 

It was pretty easy to fix, but it took me some time to figure it out.

I also found out that I had to pay attention also to my query string, because if it wasn't a place in GeoNames,  geocode method throws a TypeError exception, so I had to wrap it in a try-except statement to handle that case.

By the way, notice that Geopy allows you to query not only GeoNames, but "Yahoo! Maps, Windows Local Live (Virtual Earth), geocoder.us, MediaWiki pages (with the GIS extension), and Semantic MediaWiki pages".

If you have any other question just ask me, and leave me a comment to tell me if this post was helpful!

Commenti

Posta un commento