Feed this CGI script the name of a place and it will give you it's longitude and latitude. Entering the search phrase in the format 'country, city' will give a more accurate result. A Google maps API key is required.
| Python |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import urllib
from time import sleep
print 'Content-type: text/html\n\n'
print '<head><title>CO-ORDINATES</title></head>'
key = "YOUR-GOOGLE_MAPS-API-KEY"
def location2latlong(query, key=key):
"""Get the ( latitute, longitude ) coordinates corresponding
to the query. If something goes wrong return None."""
output = 'csv'
params = {}
params['key'] = key
params['output'] = output
params['q'] = query
params = urllib.urlencode(params)
try:
f = urllib.urlopen("http://maps.google.com/maps/geo?%s" % params)
except IOError:
# maybe some local problem at google? let's try again
sleep(3)
try:
f = urllib.urlopen("http://maps.google.com/maps/geo?%s" % params)
except IOError:
# okay we give up
return None
response = f.read().split(',')
f.close()
try:
status = response[0]
accuracy = response[1]
latitude = response[2]
longitude = response[3]
except:
return None
if status != '200':
return None
else:
return latitude, longitude
if __name__ == '__main__':
import cgi
form = cgi.FieldStorage()
r = None
if not r:
print """
<head><title> CO-ORDINATES</title></head>
<form method="post" action="co-ordinates">
<input type="text" name="location"><br>
<input type="submit" value="Get Co-ordinates"><br>"""
if not form.has_key('location'):
exit(-1)
q = form.getvalue('location')
r = location2latlong(q)
if r is not None:
print """
<head><title>CO-ORDINATES</title></head>
<b><font color='bage'>
[ %s ] |||> %s Latitude ::: %s Longitude
</font></b>
""" % (q, r[0], r[1])
else:
print '%s? Sorry, never heard of it.' % q
|
Discussion
Experimenting with Google maps and Python.


Comments
Hi. I am trying to run this script with my API GoogleMaps key in linux, with no results but:
Any ideas why? Thanks.
Sign in to comment