以下是使用高德API规范地址的 Python完整代码,包含详细的注释和错误处理:
import requests
from urllib.parse import quote
def standardize_gaode_address(raw_address, api_key):
"""
使用高德API规范地址
:param raw_address: 原始地址(如:"江苏省盐城市紫薇国际广场b3栋")
:param api_key: 高德Web服务API Key
:return: 标准化后的地址信息(字典格式)
"""
# 1. 对地址进行URL编码
encoded_address = quote(raw_address)
# 2. 构建API请求URL
url = f"https://restapi.amap.com/v3/geocode/geo?address={encoded_address}&key={api_key}"
try:
# 3. 发送GET请求
response = requests.get(url, timeout=10) # 设置10秒超时
result = response.json()
# 4. 检查API返回状态
if result["status"] != "1":
error_info = result.get("info", "未知错误")
return {"error": f"API请求失败: {error_info}"}
# 5. 解析标准化地址
if result["count"] == "0":
return {"error": "未找到匹配地址"}
geocode_data = result["geocodes"][0]
# 6. 提取结构化信息
standardized = {
"formatted_address": geocode_data["formatted_address"], # 完整标准化地址
"province": geocode_data["province"], # 省
"city": geocode_data["city"], # 市
"district": geocode_data["district"], # 区
"street": geocode_data.get("street", ""), # 街道(可能为空)
"number": geocode_data.get("number", ""), # 门牌号
"location": geocode_data["location"] # 经纬度
}
return standardized
except requests.exceptions.Timeout:
return {"error": "请求超时,请检查网络"}
except Exception as e:
return {"error": f"系统错误: {str(e)}"}
# 使用示例 ---------------------------------------------------------------------
if __name__ == "__main__":
# 替换为你的高德API Key
YOUR_API_KEY = "你的高德Web服务Key"
# 原始地址
raw_address = "江苏省盐城市紫薇国际广场b3栋"
# 调用函数
result = standardize_gaode_address(raw_address, YOUR_API_KEY)
# 打印结果
if "error" in result:
print(f"错误信息: {result['error']}")
else:
print("【标准化地址】", result["formatted_address"])
print("【行政区划】", f"{result['province']} {result['city']} {result['district']}")
print("【街道信息】", f"{result['street']}{result['number']}")
print("【经纬度】", result["location"])
urllib.parse.quote
处理中文字符,避免乱码问题{
"formatted_address": "江苏省盐城市亭湖区紫薇国际广场B3栋", # 完整规范地址
"province": "江苏省",
"city": "盐城市",
"district": "亭湖区",
"street": "紫薇路", # 可能为空
"number": "B3栋", # 可能为空
"location": "120.123456,33.654321" # 经纬度
}
YOUR_API_KEY
【标准化地址】 江苏省盐城市亭湖区紫薇国际广场B3栋
【行政区划】 江苏省 盐城市 亭湖区
【街道信息】 紫薇路B3栋
【经纬度】 120.123456,33.654321
通过这个代码,你可以: