Python获取地区的经纬度(高德API)

这两天我的朋友在写毕业论文(非计算机专业),让我帮写一个代码,输入是一些地址,然后给出其经纬度,并且告诉我高德已经有相关的API。地址是一个excel表,类似如下:

高德文档如下:https://lbs.amap.com/api/webservice/guide/api/georegeo

我直接给出我的实现代码,输出到新文件中,类似这样:

运行效果大概如下,我加了一个进度条,可以方便查看:

源代码如下: 

import requests
import openpyxl
import json
from openpyxl import load_workbook
import time
from tqdm import tqdm
# 高德API配置
AMAP_KEY = ''  # 替换为你的实际API密钥
AMAP_URL = 'https://restapi.amap.com/v3/geocode/geo?parameters'

def get_coordinates(address, max_retries=3):
    """通过高德API获取地址的经纬度"""
    params = {
        'key': AMAP_KEY,
        'address': address,
        'output': 'JSON'
    }
    
    for attempt in range(max_retries):
        try:
            response = requests.get(AMAP_URL, params=params, timeout=10)  # 10秒超时
            data = response.json()
            
            if data['status'] == '1' and data['geocodes']:
                location = data['geocodes'][0]['location']
                return location.split(',')  # 返回经度,纬度
            return None, None
            
        except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
            if attempt == max_retries - 1:
                print(f"\n地址 '{address}' 处理失败: {str(e)}")
                return None, None
            time.sleep(2 ** attempt)  # 指数退避

def process_excel(input_file, output_file):
    """处理Excel文件"""
    wb = load_workbook(input_file)
    ws = wb.active
    
    # 添加新列标题
    ws.cell(row=1, column=ws.max_column+1, value='经度')
    ws.cell(row=1, column=ws.max_column+1, value='纬度')
    
    # 从第二行开始处理地址(添加进度条)
    for row in tqdm(range(2, ws.max_row + 1), desc="处理进度"):
        address = ws.cell(row=row, column=1).value  # 假设地址在第一列
        if address:
            lng, lat = get_coordinates(address)
            ws.cell(row=row, column=ws.max_column-1, value=lng)
            ws.cell(row=row, column=ws.max_column, value=lat)
            time.sleep(0.5)
    
    wb.save(output_file)

if __name__ == '__main__':
    input_excel = '国家级_新20250422.xlsx'  # 输入文件路径
    output_excel = 'addresses_with_coords_国家级_新20250422.xlsx'  # 输出文件路径
    process_excel(input_excel, output_excel)

如果显示缺少库,一个一个安装即可,(最好使用国内的源,比如清华源)

比如:

pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值