import pandas as pd
import requests
import json
AK = "********"
# place = "甘肃省庆阳市合水县"
def getCoordinates(place):
url = f"https://api.map.baidu.com/geocoding/v3/?address={place}&output=json&ak={AK}"
res = requests.get(url)
json_data = json.loads(res.text)
if json_data["status"] == 0:
return json_data["result"]["location"]["lat"], json_data["result"]["location"]["lng"]
else:
return "no data", json_data["status"]
# print(getCoordinates("甘肃省庆阳市合水县"))
def adminDivision(lat, lng):
url = f"https://api.map.baidu.com/reverse_geocoding/v3/?ak={AK}&output=json&coordtype=gcj02ll&language=zh-CN&location={lat},{lng}"
res = requests.get(url)
json_data = json.loads(res.text)
if json_data["status"] == 0:
return json_data["result"]["addressComponent"]["province"], json_data["result"]["addressComponent"]["city"], json_data["result"]["addressComponent"]["district"]
else:
return "no data", "no data", "no data"
# lat, lng = getCoordinates("红古区花庄镇湟兴村")
# print(adminDivision(lat, lng))
if __name__ == "__main__":
data = pd.read_csv("xaquyu.csv")
res = []
for i in range(len(data)):
province = data.iloc[i,0]
address = data.iloc[i,1]
place = province + address
lat, lng = getCoordinates(place)
res_province, res_city, res_district = adminDivision(lat, lng)
res.append([province, address, res_province, res_city, res_district])
pd.DataFrame(res).to_csv(
"result_quyu.csv",
header=["省份", "目的地", "省", "市", "区县"],
encoding="utf-8-sig",
index=False
)
|