参考链接:https://blog.csdn.net/xHibiki/article/details/90377192
百度地图API需要申请并创建应用才能使用,得到AK。
参考文档:http://lbsyun.baidu.com/index.php?title=uri/api/web
输入纬度、经度,输出所在城市名:
import requests
import urllib
import hashlib
#1 输入纬度、经度
lat,lon=input("输入地区所属的纬度、经度\n").split(" ")
#2 计算校验SN(百度API文档说明需要此步骤)
ak="xxxxxx" # 参照自己的应用
sk="xxxxxx" # 参照自己的应用
url = "http://api.map.baidu.com"
query ="/geocoder/v2/?callback=renderReverse&location={0},{1}&output=json&pois=1&latest_admin=1&ak={2}".format(lat, lon, ak)
encodedStr = urllib.parse.quote(query, safe="/:=&?#+!$,;'@()*[]")
sn=hashlib.md5(urllib.parse.quote_plus(encodedStr + sk).encode()).hexdigest()
#3 使用requests获取返回的json
response=requests.get("{0}{1}&sn={2}".format(url,query,sn))
data=response.text
#4 处理json
city_name=eval(data[29:-1])['result']['addressComponent']['city']
print(data)
print(city_name)
实际返回的data中包含更详细的地址,这里只取了城市名:
renderReverse&&renderReverse({"status":0,"result":{"location":{"lng":-71.05888009999998,"lat":42.3516529830582},"formatted_address":"129 Lincoln Street, Boston, Massachusetts, United States","business":"","addressComponent":{"country":"United States","country_code":54003,"country_code_iso":"USA","country_code_iso2":"US","province":"Massachusetts","city":"Boston","city_level":2,"district":"","town":"","adcode":"0","street":"Lincoln Street","street_number":"129","direction":"西北","distance":"76"},"pois":[],"roads":[],"poiRegions":[],"sematic_description":"","cityCode":55512}})