本文介绍 Python 语言使用高德地图 API,搜索 POI 获取地理信息的代码实现。
高德地图 API 搜索 POI:
https://lbs.amap.com/api/webservice/guide/api/search
1. post 请求
import requests
import json
url_base = "https://restapi.amap.com/v3/place/text?"
str_keywords = '|'.join(list_keyword) # list_keyword: 多个关键字用“|”分割,list_type同
piece_keywords = "&keywords={}".format(str_keywords) if list_keyword else ""
str_types = '|'.join(list_type)
piece_types = "&types={}".format(str_types) if list_type else ""
url = "{base}" \
"key={key}" \
"{keywords}" \
"{types}" \
"&city={city}" \
"&citylimit={city_limit}" \
"&children={children}" \
"&offset={offset}" \
"&page={page}" \
"&extensions={extensions}" \
"&output={output}".format(base=url_base,
key=key, # ak
keywords=piece_keywords, # 关键字,关键字和POI类型两者至少必选其一
types=piece_types, # POI类型
city=city, # 查询城市,可选值:城市中文、中文全拼、citycode、adcode
city_limit=city_limit, # 是否仅返回指定城市数据
children=children, # 是否按照层级展示子POI数据:0: 子POI都会显示;1: 子POI会归类到父POI之中
offset=offset, # 每页记录数据,强烈建议不超过25,若超过25可能造成访问报错
page=page, # 当前页码
extensions=extensions, # 返回结果控制:'base', 返回基本地址信息;'all': 返回地址信息、附近POI、道路以及道路交叉口信息
output=output) # 返回数据格式类型,{'JSON', 'XML'}
response = requests.get(url=url).content
json_res = json.loads(response)
注:
POI城市编码 / 城市编码表:
https://lbs.amap.com/api/webservice/download
2. 查询
import math
import pandas as pd
from utils.logger import log
try:
key = list_key[0] # ak列表
# 首次请求,获取页数
first_page = get_post(key=key, page=1)
num_page = math.ceil(int(first_page['count']) / offset)
log.info(msg="POI 数量: {}".format(first_page['count']))
log.info(msg="总页数: {}".format(num_page))
df_info = df_info.append(pd.DataFrame(first_page['pois'])) # 保存首页结果,节约请求次数
for page in range(2, num_page + 1):
log.info(msg="城市 {city} 页码 {page} 正在查询".format(city=city, page=page))
try:
current_page = get_post(key=key, page=page)
# 如果ak的查询次数达到上限,更换ak
if current_page['status'] == '0' and current_page['info'] == '10003':
log.error(msg="key {key} 查询次数达到上限".format(key=key))
list_key.pop(0)
key = list_key[0]
log.info(msg="key {key} 正在使用中".format(key=key))
current_page = get_post(key=key, page=page)
# 查询成功,存储结果
if current_page['status'] == '1':
df_info = df_info.append(pd.DataFrame(current_page['pois']))
# 其他失败原因
else:
log.error(msg="{}".format(current_page['info']))
except Exception as e:
log.error(msg=str(e))
continue
except Exception as e:
log.error(msg=str(e))
注:
有关 log,参考日志的写法
https://blog.csdn.net/Zhang_0702_China/article/details/107982958
错误码说明:
https://lbs.amap.com/api/webservice/guide/tools/info
3. 结果处理
df_info.rename(columns={'parent': '父POI',
'address': '地址',
'distance': '到中心点距离',
'biz_ext': '深度信息',
'pname': '省份',
'biz_type': '行业类型',
'cityname': '城市',
'type': '类型',
'photos': '照片',
'typecode': '类型编码',
'adname': '区县',
'name': '名称',
'location': '经纬度',
'tel': '电话',
'id': 'ID'}, inplace=True)
df_res = df_info[['省份', '城市', '区县', '名称', '地址', '经纬度', '电话', 'ID']].copy()