google maps api for py?
Daniel Nogradi
nogradi at gmail.com
Wed May 30 12:34:11 EDT 2007
> I see that the weapon of choice for google maps is javascript... Is
> there anything for python?
I wrote the following for finding the latitude/longitude of a
location. You need to set the variable 'key' to the actual key you got
from google.
(Indentation might get mixed up on the way.....)
HTH,
Daniel
###############################
# gmaps.py
###############################
import urllib
from time import sleep
key = "here_goes_your_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 sys
try:
q = sys.argv[1]
except:
print 'Usage: python gmaps.py query'
sys.exit( 1 )
r = location2latlong( q )
if r is not None:
print r
else:
print 'Something went wrong.'
###############################
###############################
More information about the Python-list
mailing list