Python-遍历地址表,使用函数进行地理定位,将lat / long复制到行?

时间:2018-04-15 12:18:47

标签: python geolocation arcpy

我有一个地址表,我需要我的Python脚本才能使用我的Google API地理定位功能为每个地址返回纬度/经度坐标,并为每个地址添加到同一行的新字段。地理编码功能工作正常 - 我只是不能让脚本迭代遍历表的每一行,将地址添加到函数中,然后将输出lat / long复制到同一行中的字段。这就是我所拥有的:

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);

1 个答案:

答案 0 :(得分:0)

您使用字符串'地址'

调用geolocate函数
field1 = 'address'
geo = geolocate(address = field1)

您希望使用实际地址调用geolocate,这意味着您需要在循环游标的循环中执行此操作。所以它应该是这样的:

fields = [field1, field2])
with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        address = row[0]
        geo = geolocate(address = address)
        row[1] = geo[0], geo[1]
        cursor.updateRow(row)

注意:我使用了ArcGIS 10.1中引入的数据访问模块中的光标。我还使用了'和#39;游标的语法,以便它自动处理删除游标。