iamtgc

Geocoding with Python

July 25th, 2007 by tgc

The following code snippet is intended to demonstrate how you can leverage Python and the Google Maps/Geocode API to query the coordinates of two zip codes and then determine the distance between them. Both functions have far reaching uses independently which will be further demonstrated in future posts.

This example determines distance between the two points in miles, however it can be modified to return distance in kilometers by replacing 3959.0 (the average radius of the earth in miles) with 6371.0 (the radius in kilometers).

This code does no validation on the existence of the zip code, and will likely return valid coordinates of something (whatever Google thinks you really meant) when you pass it a non existent zip code.

The original geocode code was found here.

Note: You will have to provide your Google Maps API key in the key variable.

import math import urllib def get_lat_long(location): key = "" output = "csv" location = urllib.quote_plus(location) request = "http://maps.google.com/maps/geo?q=%s&output=%s&key=%s" % (location, output, key) data = urllib.urlopen(request).read() dlist = data.split(',') if dlist[0] == '200': return dlist[2], dlist[3] else: return None, None def calculate_distance(zip1, zip2): lat1, lon1 = get_lat_long(zip1) lat2, lon2 = get_lat_long(zip2) if (not lat1) or (not lon1) or (not lat2) or (not lon2): return -1 lat1 = float(lat1) * math.pi/180 lon1 = float(lon1) * math.pi/180 lat2 = float(lat2) * math.pi/180 lon2 = float(lon2) * math.pi/180 return 3959.0 * math.acos(math.sin(lat1) * math.sin(lat2) + math.cos(lat1) * math.cos(lat2) * math.cos(lon2-lon1))

Posted in Google, Python

One Response

  1. Zach

    It works wonderfully!

    Thank you!

    (by the way– google limits their number of geocodes per day, so be careful!)

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.