• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
OctoberOrange
博客园    首页    新随笔    联系   管理    订阅  订阅
通过百度地图地理查询和逆地址查询
# 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={}&region=标注范围&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')

 

posted on 2024-04-26 10:16  十月的橙子  阅读(80)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3