利用百度地图API提供的全球逆地理编码服务可以实现经纬度批量转地址的功能。
这是API给出的GET请求:
https://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194
可以看到,加粗的部分为需要用户自己设置的参数。这里简单说明一下这几个参数的含义(懒得看的朋友可以直接跳过)直接copy代码跑就好~
- ak即百度地图API的密钥,需要自行申请,网上教程很多这里随便放一个https://lbsyun.baidu.com/index.php?title=jspopular3.0/guide/getkey 注意一定要选择服务器端!
- wgs84是一种坐标系,这里根据数据的坐标系自行设置,因为在不同坐标系下同一坐标所对应的地方是不一样的。常见的坐标系有bd09ll(百度经纬度坐标);bd09mc(百度摩卡托坐标);gcj02(国测局加密坐标),wgs84(gps设备获取的坐标)……
- location即经纬度坐标啦。
所以整个过程的重点就是文件的读写和输出了,简单分析后就可以写代码啦~
# -*- coding: utf-8 -*-
"""
import pandas #读取excel表
import json #数据格式转换
from urllib.request import urlopen #获取网页
# 原数据文件格式: 纬度 + 经度
origin_path = r'路径' # 原始坐标文件路径
result_path = r'保存路径' # 爬取数据文件保存路径
"""# 百度地图提供的api服务网址
'https://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194'
"""
AK = ['你申请的ak']
dfBase = pandas.read_excel(origin_path)
# dfBase.head()
dataList = [] # 储存获取的路线数据
for i in range(0,n): #有多少数据n就写多少
print( i )
out_lat = dfBase.at[i, '纬度']
out_lng = dfBase.at[i, '经度']
url_Geocoder = r"https://api.map.baidu.com/reverse_geocoding/v3/?ak=AK&output=json&coordtype=bd09llll&location={0},{1}".format(out_lat, out_lng)
result_Geocoder = json.loads(urlopen(url_Geocoder).read()) # json转dict
status_Geocoder = result_Geocoder['status']
if status_Geocoder == 0: # 状态码为0:无异常
loc = result_Geocoder['result']['formatted_address']
dataList.append([loc])
dfAll = pandas.DataFrame(dataList, columns=['loc'])
dfAll.to_excel(result_path)
print('Done!')
欢迎评论区交流!