对于单个地址基于Python中的geocoder库获取经纬度非常方便,代码如下:
# coding=utf-8
import geocoder
# 输入地址
address = 'Akala Temple'
lonLat = geocoder.osm(address)
print(lonLat.latlng)
# 输出结果 [27.8569644, 84.0893767]
若地址数量较多,可参考如下代码批量处理并写入表格:
# coding=utf-8
import geocoder
import pandas as pd
import csv
import re
y = []
times = 0
# 导入需要地理编码的.csv文件
with open('text.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
place = row[0]
print('地址:'+place)
ret = geocoder.osm(place, timeout=5.0) #响应时间在5秒内
resLatLon = str(ret.latlng)
try:
pat = "(.*?),"
res = re.compile(pat).findall(resLatLon)[0]
lon = res.strip('[')
print("经度:" + lon)
pat1 = ", (.*?)]"
lat = re.compile(pat1).findall(resLatLon)[0]
print("纬度:" + lat)
except:
print('地址'+row[0]+'转换失败')
lon = 'none'
lat = 'none'
times += 1
print('已转换'+str(times)+'条地址')
print('-----------------------------------------------')
y.append([row[0],lon,lat])
# 转换结果写入表格
result = pd.DataFrame(y)
result.columns = ['地址','纬度','经度']
result.to_csv('地理编码结果.csv',encoding='utf-8-sig', index=False)