I have always avoided Python. I am not sure why, but I think it is mostly because of the syntax, with the needed indention. Well, today I wrote my first script, and I actually like the language a little.
I needed to lookup GPS coordinates for a long list of addresses, and didn’t like doing it manually. Using Google’s maps API, I solved the problem with this little script. It reads the addresses from stdin and writes addresss;latitude;longtitude to stdout.
#!/usr/bin/env python
# Importing modules
import urllib
import json
import sys
# Configuration of main URL
URL = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
# Read addresses from stdin
for address in sys.stdin:
#print "Looking up: " + str(address)
# URL Encode the address
encoded_address = urllib.quote(address.strip())
real_url = URL + encoded_address
# Reset buffer
buffer = ''
# Fetch the json result
try:
fh = urllib.urlopen(real_url)
for line in fh:
buffer += line
fh.close
except Exception:
print "Ops, caught an exception."
sys.exit(1)
# Try to de-serialize the json string
result = json.loads(buffer)
# Check status of result
if result['status'] == "OK":
#print "Results looks good, continue"
for r in result['results']:
lat = str(r['geometry']['location']['lat'])
lng = str(r['geometry']['location']['lng'])
print '%s; lat=%s; lng=%s' % (address.strip(), lat, lng)
# Finish