Determining country by latitude/longitude

Yesterday I talked about how I used censorship research) where the API will report longitude and latitude but not always country.

To solve this problem, I decided to make use of the Google Maps API, specifically the subset of the API that deals with geocoding. You can look through the specifics easily enough, but the general idea is just to use a specific URL:{latitude},{longitude}&sensor=false

The result will be a json encoded list of results, each of which can have one or more address_components. Those can be all sorts of things–routes, political regions, countries, buildings; all sorts. Long story short, for this project, we’re looking for a country. As soon as we find one, return it.

Luckily, Python makes fetching urls and dealing with json really straight forward:

# Get a country from a latitude and longitude
def lookup(lat, lon):
	data = json.load(urllib2.urlopen(',%s&sensor=false' % (lat, lon)))

	for result in data['results']:
		for component in result['address_components']:
			if 'country' in component['types']:
				return component['long_name']

	return None

Trying it out:

>>> lookup(39.16554,-86.523525)
u'United States'

And that’s all there is to it. You can map this over much larger lists of latitudes and longitudes, although if you abuse it, expect to be rate limited.