言归正传~
通过python调用高德地图接口,返回经纬度
代码如下:
import xlrd
import requests
import json
# 设置路径
path = './lj_distinct_data_analysis.xlsx'
# 打开execl
workbook = xlrd.open_workbook(path)
# 输出Excel文件中所有sheet的名字
print(workbook.sheet_names())
# 根据sheet索引或者名称获取sheet内容
Data_sheet = workbook.sheets()[0] # 通过索引获取
colNum = Data_sheet.ncols # sheet列数
rowNum = Data_sheet.nrows # sheet行数
cols = Data_sheet.col_values(colNum - 1) # 获取最后一列内容
print(cols)
address_all = []
url = "https://restapi.amap.com/v3/geocode/geo"
if rowNum > 2:
# 循环地址
count = 1
address = ''
for rowCount in range(1, rowNum):
# 10次请求或者是最后一次请求未满10次
if (count % 10 == 0 or count == rowNum):
if (address == ''):
address += cols[rowCount] # address 首地址不能有‘|’
else:
address += '|' + cols[rowCount]
# 参数
content = {'key': '********************', 'address': address, 'batch': 'true'}
# print(content)
# get 请求
response = requests.get(url, params=content)
# 字符串转json
json_obj = json.loads(response.text)
# {
# "status": "1",
# "info": "OK",
# "infocode": "10000",
# "count": "1",
# "geocodes": [
# {
# "formatted_address": "北京市朝阳区阜通东大街|6号",
# "country": "中国",
# "province": "北京市",
# "citycode": "010",
# "city": "北京市",
# "district": "朝阳区",
# "township": [],
# "neighborhood": {
# "name": [],
# "type": []
# },
# "building": {
# "name": [],
# "type": []
# },
# "adcode": "110105",
# "street": "阜通东大街",
# "number": "6号",
# "location": "116.483038,39.990633",
# "level": "门牌号"
# }
# ]
# }
# 获取到listObject
geocodes = json_obj.get('geocodes')
if geocodes is not None:
for obj in geocodes:
# 获取到list的 第一个中location的值
addressAndLocation = obj.get('formatted_address') + ":" + obj.get('location')
print(addressAndLocation)
if addressAndLocation is not None:
address_all.append(addressAndLocation)
address = '' # 10次之后重新初始化
else:
if (address == ''):
address += cols[rowCount]
else:
address += '|' + cols[rowCount]
count += 1
print(len(address_all))
import pandas as pd
address_all = pd.Series(address_all)
address_all = address_all.str.split(r':',expand = True)
address = address_all[0]
jingweidu = address_all[1].str.split(r',',expand = True)
name ={n:v for n,v in zip([0,1],['经度','纬度'])}
jingweidu.rename(columns=name,inplace=True)
dizhi = pd.concat([address,jingweidu],axis=1)
dizhi.rename(columns={0:'addr'},inplace=True)
dizhi.head()
#保存到execl
dizhi.to_excel(r'.\经纬度返回.xlsx')