Archive | February, 2013

Python Function to Geocode an Address Using Google

7 Feb

I stole this from a python networking book – a great book!!- and made it into a function by allowing the user to enter an address and with a return value array contains the longitude and latitude. Enter an address in the format STREET, CITY,STATE ABBREVIATION:

>>>Import google
>>>A=google.longlat()
Address: 100 10th st, Albuquerque,nm
>>>A[0] # returns the longitude
-106.659
>>>A[1] # returns the latitude
35.1234

Here is the function-I saved it as google.py:

import urllib, urllib2, json

def latlong():
address=raw_input(“address:”)
param = {‘q’: address,’output’: ‘json’, ‘oe’: ‘utf8’}
url = ‘http://maps.google.com/maps/geo?’ + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = json.loads(rawreply)
a=[]
a.append(reply[‘Placemark’][0][‘Point’][‘coordinates’][0])
a.append(reply[‘Placemark’][0][‘Point’][‘coordinates’][1])
return a

Advertisements