最近公司项目需要批量获取Excel中地址,将地址转换成对应的经纬度,用到的是腾讯地图API。
进入官网–>腾讯地图
进入开发文档–>地址坐标相互转换
文档中请求链接,请求参数,返回参数都很清晰,这里直接把调用代码写上来。
(开发者需要先注册获取API使用权限)
地址转坐标
developer_key = "" #API控制台KEY管理中的KEY
# 通过地址获取经纬度
def address_coordinate_post_request(address):
parameters = {'address': address, 'key': developer_key, 'region': '武汉'}
base = "http://apis.map.qq.com/ws/geocoder/v1/?" # 地址转坐标
response = requests.get(base, parameters)
answer = response.json()
print(answer)
if(answer['status'] == 0):
data = {
'lng':answer['result']['location']["lng"], # 经度
'lat':answer['result']['location']["lat"] # 纬度
}
else:
data = {
'lng':'error',
'lat':'error'
}
return data
坐标转地址
developer_key = "" #API控制台KEY管理中的KEY
# 通过经纬度来获取地址
def coordinate_to_address(lat_lng): # 注意入参格式:纬度,经度
base = "https://apis.map.qq.com/ws/geocoder/v1/?location={}&get_poi={}&key={}".format(lat_lng, 1, developer_key) # 坐标转地址
response = requests.get(base)
answer = response.json()
# print(answer)
if(answer['status'] == 0):
data = answer['result']['address']
else:
data = 'error'
print(data)
return data
直接上代码:
# -*- coding:utf-8 -*-
# author:ck_233 time:2020/3/16
import time
import requests
import pandas as pd
from pandas import DataFrame
developer_key = '' # 这里为你申请的开发者key
# 通过地址获取经纬度
def address_to_coordinate(address):
base = "http://apis.map.qq.com/ws/geocoder/v1/?address={}&key={}".format(address, developer_key) # 地址解析,地址转坐标
response = requests.get(base)
answer = response.json()
if(answer['status'] == 0):
data = {
'lng':answer['result']['location']["lng"], # 经度
'lat':answer['result']['location']["lat"] # 纬度
}
else:
data = {
'lng':'error',
'lat':'error'
}
print(data)
return data
# 通过经纬度获取地址
def coordinate_to_address(lat_lng): # 注意入参格式:纬度,经度
base = "https://apis.map.qq.com/ws/geocoder/v1/?location={}&get_poi={}&key={}".format(lat_lng, 1, developer_key) # 坐标转地址
response = requests.get(base)
answer = response.json()
# print(answer)
if(answer['status'] == 0):
data = answer['result']['address']
else:
data = 'error'
print(data)
return data
# 入参excel文件名,表名
def readExcel(filename, sheetname):
data = pd.read_excel(filename, sheetname)
# print(data)
# 通过地址获取经纬度,并修改
for index in range(0,len(data)):
# 开发者并发有限制,根据情况来设置
time.sleep(0.2)
print(data.loc[index, '地址'])
address = data.loc[index, '地址']
lng_lat = address_to_coordinate(address)
data.loc[index, '经度'] = lng_lat['lng']
data.loc[index, '纬度'] = lng_lat['lat']
# print(data)
# 保存修改
DataFrame(data).to_excel(filename, sheet_name=sheetname, index=False, header=True)
if __name__ == '__main__':
# address_to_coordinate("武汉市青山区和平大道809号")
# coordinate_to_address("30.617353,114.360809")
readExcel('xxxx.xlsx', 'Sheet1')