这段代码的主要作用是通过调用高德开放平台的API来获取指定位置的经纬度坐标。
高德开放平台API获取方法在文末。
介绍一下代码及使用方法:
代码语言:python
位置输入方式:Excel文件
位置输出方式:Excel文件
实现效果如下图:
代码如下:
import json
import time
from urllib.request import urlopen
from urllib.parse import quote
import openpyxl
def Getlnglat(address):
root_url = 'https://restapi.amap.com/v3/geocode/geo'
output = 'json'
ak = "d2cbbbaedd5613c074cc8" # 替换为你的 API
add = quote(address)
url = f'{root_url}?address={add}&output={output}&key={ak}'
try:
req = urlopen(url)
res = req.read().decode()
temp = json.loads(res)
if temp['status'] == '1' and temp['geocodes']:
location = temp['geocodes'][0]['location']
lng, lat = location.split(',')
return lng, lat
else:
return None, None
except Exception as e:
print(f"Error fetching data for {address}: {e}")
return None, None
def Analy(file_path):
wb = openpyxl.load_workbook(file_path)
ws = wb.active
ws.cell(1, 2).value = '经度'
ws.cell(1, 3).value = '纬度'
for i in range(2, ws.max_row + 1):
try:
address = ws.cell(i, 1).value
lng, lat = Getlnglat(address)
if lng and lat:
ws.cell(i, 2).value = lng
ws.cell(i, 3).value = lat
print(f"{address}: 经度={lng}, 纬度={lat}")
else:
ws.cell(i, 4).value = "无法获取坐标,请重新尝试"
except Exception as e:
ws.cell(i, 4).value = f"Error: {e}"
time.sleep(3)
wb.save(file_path)
Analy(file_path='3.xlsx') #替换为你的文件路径(请保证路径正确)
大家用以上代码的时候有两处需要改动:
第一个就是第十行:
ak = "d2cbbbaedd5613c074cc8" # 替换为你的 API
第二个是最后一行:
Analy(file_path='3.xlsx') #替换为你的文件路径(请保证路径正确)
然后就能批量获取指定位置的经纬度坐标了。
另外,如果大家不知道高德API如何申请,请按照这个文档来操作:
使用代码前请确认相关的库正确安装。
欢迎大家使用上述代码,如果有什么问题,请留言或者在公众号后台私信我。
如果你有什么好的想法或者需求,也请告诉我,我会尽力满足。
如果以上内容对你有帮助,麻烦您给我点个免费的赞,您的支持是我创作的最大动力。
原文链接: