我正在尝试用python和模块地理编码器进行反向地理编码
我构建了这个脚本
#!/Users/admin/anaconda/bin/python
import geocoder
import unicodecsv
import logging
with open('locs2.csv', 'rb') as f:
reader = unicodecsv.DictReader(f, encoding='iso-8859-1')
for line in reader:
lat = line['lat']
lon = line['lon']
g = geocoder.google(['lat','lon'], method=reverse)
if g.ok:
g.postal
logging.info('Geocoding SUCCESS: ' + address)
else:
logging.warning('Geocoding ERROR: ' + address)
根据文件here,我们可以做反向。但是,当我运行脚本时,出现此错误NameError: name 'reverse' is not defined
为什么?
TIA
这是我文件中的示例
lat, lon
48.7082,2.2797
48.7577,2.2188
47.8333,2.2500
48.9833,1.7333
47.9333,1.9181
46.2735,4.2586
**编辑**:我已经修改了一下脚本(见下文),我有这个错误
WARNING:root:Geocoding ERROR:
修改后的脚本
#!/Users/admin/anaconda/bin/python
import geocoder
import unicodecsv
import logging
pcode=[]
lat=[]
lon=[]
with open('locs2.csv', 'rb') as f:
reader = unicodecsv.DictReader(f, encoding='iso-8859-1')
for line in reader:
lat = line['lat']
lon = line['lon']
g = geocoder.google([lat,lon], method='reverse')
if g.ok:
pcode.extend(g.postal)
logging.info('Geocoding SUCCESS: '+
str(lat)+','+str(lon)+','+str(pcode))
else:
logging.warning('Geocoding ERROR: ' + str(lat)+','+str(lon))
fields= 'lat', 'lon', 'pcode'
rows=zip(lat,lon,pcode)
with open('/Users/admin/python/myfile.csv', 'wb') as outfile:
w = unicodecsv.writer(outfile, encoding='iso-8859-1')
w.writerow(fields)
for i in rows:
w.writerow(i)
答案 0 :(得分:3)
答案 1 :(得分:2)
问题是您忘记在选项reverse
周围添加引号:
g = geocoder.google(['lat','lon'], method='reverse')
我认为他们的文档中存在错误。您可以向作者发送消息以通知他/她,他/她可能想要更新他们的文档。
此外,您希望使用实际参数lat
和lon
来调用它,而不是字符串。否则你会收到错误。
所以,
g = geocoder.google([lat, lon], method='reverse') # lat and lon you've extracted already, but maybe you'll still need to cast them to float.
更新:如果您正在运行提供g.ok == False
的反向查询,则问题与API提供商对请求的限制有关(在上面的示例中) ,这是谷歌)。例如,Google Maps API specifies fair use并且不应过快地轮询。致电g.debug()
时,此信息很明确。其中的输出将是:
## Provider's Attributes
* status: OVER_QUERY_LIMIT
* error_message: You have exceeded your rate-limit for this API.
要限制您的请求,您可以执行以下操作:
import geocoder
import unicodecsv
import logging
import time
import csv
pcode=[]
with open('locs2.csv', 'rb') as f:
reader = csv.DictReader(f)
for line in reader:
lat = float(line['lat'])
lon = float(line['lon'])
g = geocoder.google([lat,lon], method='reverse')
attempts = 1 # number of lookups
while not(g.ok) and attempts < 4:
logging.warning('Geocoding ERROR: {}'.format(g.debug()))
time.sleep(2) # 2 seconds are specified in the API. If you still get errors, it's because you've reached the daily quota.
g = geocoder.google([lat,lon], method='reverse')
attempts += 1
if attempts > 3:
logging.warning('Daily quota of google lookups exceeded.')
break
pcode.extend(g.postal)
logging.info('Geocoding SUCCESS: ({},{},{})'.format(lat,lon,pcode))
一些提供商,例如Mapquest,暂时不会施加限制。
地理编码器版本0.9.1中存在的一个错误是,lat
和lon
都应与0.0
不同。如果您有这样的坐标(沿着赤道或Greenwhich子午线),查找将生成TypeError
。