# coding:utf-8 from urllib.request import quote import requests import pandas as pd pd.set_option('display.width', 1000) pd.set_option('display.max_columns', None) import json # 通过百度地图地理查询和逆地址查询 def get_location(address): try: url = 'http://api.map.baidu.com/place/v2/search?query={}®ion=标注范围&output=json&ak=你的ak&scope=2'.format(quote(address)) response = requests.get(url) result = response.json() if result['status'] == 0 and result['results']: lng = result['results'][0]['location']['lng'] lat = result['results'][0]['location']['lat'] return lng, lat except Exception as e: print(f"Failed to get location for {address}: {e}") return '', '' def get_address(lng, lat): try: url = 'http://api.map.baidu.com/reverse_geocoding/v3/?' output = 'json' ak = 'BXottO3XSK3SKXn99fHquBoPo620cExI' uri = url + '&output=' + output + '&ak=' + ak + '&location=' + str(lat) + ',' + str(lng) response = requests.get(uri) answer = response.json() if answer['status'] == 0: address = answer['result']['formatted_address'] return address except Exception as e: print(f"Failed to get address for coordinates ({lng}, {lat}): {e}") return 'Nan' # 导入Excel文件 df = pd.read_excel('getAdress.xlsx') # 新增两列用于存储查询结果 df['经度'] = '' df['纬度'] = '' df['详细地址'] = '' print('选择通过百度地图查询经纬度(输入1)或查询地址(输入2):') i = int(input()) if i == 1: # 批量查询经纬度 for index, row in df.iterrows(): if pd.isna(row['地址']): continue lng, lat = get_location(row['地址']) df.at[index, '经度'] = lng df.at[index, '纬度'] = lat # 保存结果到新的xlsx文件 df[['经度', '纬度']].to_excel('经纬度.xlsx', index=False) print('经纬度查询结果已保存到经纬度.xlsx') elif i == 2: # 加载保存了经纬度的xlsx文件 df_lnglat = pd.read_excel('经纬度.xlsx') # 批量查询详细地址 for index, row in df_lnglat.iterrows(): lng = row['经度'] lat = row['纬度'] address = get_address(lng, lat) df.at[index, '详细地址'] = address # 输出结果并保存到新的xlsx文件 df.to_excel('详细地址.xlsx', index=False) print('详细地址查询结果已保存到详细地址.xlsx')
标签:xlsx,df,查询,地址,address,lat,lng,百度 From: https://www.cnblogs.com/OctoberOrange/p/18159400