呼叫百度api透過經緯度獲取實際地理位置資訊

201812發表於2024-03-11

需要用到百度地圖api地址編碼(有地址轉經緯度)和逆地址編碼功能(由經緯度轉標準地址省市區),去申請金鑰進行呼叫。

申請金鑰的時候不選擇sn,可以避免後面的呼叫百度地圖API報錯'211' sn校驗失敗。

地址編碼官方文件:地理編碼 | 百度地圖API SDK (baidu.com)

逆地址編碼官方文件:全球逆地理編碼 rgc 反geo檢索 | 百度地圖API SDK (baidu.com)

主要實現程式碼:

# 2.呼叫百度api實現提取地點的經緯度
def getJingWei(address):
    url = "https://api.map.baidu.com/geocoding/v3"
    params = {
        "address": address,
        "output": "json",
        "ak": "你自己的ak金鑰",
    }
    response = requests.get(url=url, params=params)
    result = response.json()
    # print(result)
    longitude = result['result']['location']['lng']  # 經度
    latitude = result['result']['location']['lat']  # 緯度
    lnglist.append(longitude)
    latlist.append(latitude)


# 3.透過經緯度獲取地址資訊(省市區)
def getAddress(lng, lat):
    response = requests.get('https://api.map.baidu.com/reverse_geocoding/v3/?ak=你自己的金鑰&output=json&coordtype=wgs84ll&location='+str(lat)+','+str(lng))
    # if response:
    #     print(response.json())
    result = response.json()
    addlist.append(result['result']['formatted_address'])
    prolist.append(result['result']['addressComponent']['province'])
    citylist.append(result['result']['addressComponent']['city'])
    districtlist.append(result['result']['addressComponent']['district'])

# 測試
print(list[0])
getJingWei(list[0])
print(lnglist[0],latlist[0])
getAddress(lnglist[0],latlist[0])
print(addlist[0])
print(prolist[0],citylist[0],districtlist[0])

執行結果如下:

總程式碼,並且輸出到指定的txt檔案中:

# -*- coding: utf-8 -*-
"""
給地址新增行政編碼
"""
import codecs
import requests
import numpy as np

"""
抽取地址,呼叫介面檢視該地址屬於哪個省市區
"""
# 1.獲取需要的地址資料
# def splittxt():
f = codecs.open('test.txt', mode='r', encoding='utf-8')
lines = f.readlines()
list = []
lnglist = []  # 經度
latlist = []  # 維度
addlist = []  # 標準地址格式省市區
alllist=[]  # 將標準地址省市區組合在一起

for line in lines:
    # print(line.strip().split("\",")[15][1:])  #測試
    list.append(line.strip().split("\",")[15][1:])
f.close()


# print(list[0])


# 2.呼叫百度api實現提取地點的經緯度
def getJingWei(address):
    url = "https://api.map.baidu.com/geocoding/v3"
    params = {
        "address": address,
        "output": "json",
        "ak": "XoERNVN2GhBcCZISCaOjTQy1WyGlFkIc",
    }
    response = requests.get(url=url, params=params)
    result = response.json()
    # print(result)
    longitude = result['result']['location']['lng']  # 經度
    latitude = result['result']['location']['lat']  # 緯度
    lnglist.append(longitude)
    latlist.append(latitude)


# 3.透過經緯度獲取地址資訊(省市區)
def getAddress(lng, lat):
    response = requests.get('https://api.map.baidu.com/reverse_geocoding/v3/?ak=XoERNVN2GhBcCZISCaOjTQy1WyGlFkIc&output=json&coordtype=wgs84ll&location='+str(lat)+','+str(lng))
    # if response:
    #     print(response.json())
    result = response.json()
    addlist.append(result['result']['formatted_address'])
    alllist.append(result['result']['addressComponent']['province']+','+result['result']['addressComponent']['city']+','+result['result']['addressComponent']['district'])



# 測試
for i in range(len(list)):
    print(list[i])
    getJingWei(list[i])
    print(lnglist[i],latlist[i])
    getAddress(lnglist[i],latlist[i])
    print(addlist[i])
    print(alllist[i])




# 將結果輸出到指定檔案中
res_all = '\n'.join(alllist)
with open('alllistrs.txt', 'w', encoding="utf-8") as f:
    f.write(res_all)

相關文章