I have a table of addresses, and I need my Python script to use my Google API geolocate function to return lat/long coordinates for each and add to a new field in the same row for each address. The geocode function works fine- I just can't get the script to iterate through each row of the table, add the address to the function, and then copy the output lat/long to the field in the same row. here's what I have:
import urllib, json, time, arcpy
arcpy.env.workspace = "D:/GIS/addr.dbf"
#sets variables, adds new field to hold lat/long coordinates
fc = 'addr.dbf'
field1 = 'address'
field2 = 'loc'
arcpy.AddField_management(fc, field2, "TEXT")
#function that uses Google API to geolocate- this part works consistently
def geolocate(address,
api="key_here",delay=4):
base = r"https://maps.googleapis.com/maps/api/geocode/json?"
addP = "address=" + address.replace(" ","+")
gUrl = base + addP + "&key=" + api
response = urllib.urlopen(gUrl)
jres = response.read()
jData = json.loads(jres)
if jData['status'] == 'OK':
resu = jData['results'][0]
finList = [resu['formatted_address'],resu['geometry']['location']
['lat'],resu['geometry']['location']['lng']]
else:
finList = [None,None,None]
time.sleep(delay)
return finList
#adds address field as text to geolocate in function, adds output lat/long
#(indexed locations 0 and 1 from the finList output)
##this is the part that doesn't work!
geo = geolocate(address = field1)
cursor = arcpy.UpdateCursor(fc, [field1, field2])
for row in cursor:
field2 = geo[0], geo[1]
cursor.updateRow(row);