根據一箇中文的地址信息,獲取該地址所對應的經緯度信息。(專業的說法是地理編碼)。編程語言:Python3,百度地圖API接口:http://lbsyun.baidu.com/index.php?title=webapi
獲取地址的經緯度大致步驟如下:
- 1.註冊百度賬號、登錄百度地圖,申請祕鑰:http://lbsyun.baidu.com/apiconsole/key?application=key
- 2.查看百度地圖中關於地址解析的服務文檔:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
- 3.Python 編寫request請求,使用GET訪問接口:http://api.map.baidu.com/geocoder/v2/?address=北京市海淀區上地十街10號&output=json&ak=您的ak&callback=showLocation //GET請求
- 4.Python解析返回的json結果,得到經緯度信息
訪問API接口需要上傳的信息:
代碼如下:
# encoding:utf-8
import requests
import time
# 此處需要ak,ak申請地址:https://lbs.amap.com/dev/key/app
ak = "xxxxxxxxxxx"
headers = {
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/56.0.2924.87 Safari/537.36',
'Referer': 'https://restapi.amap.com/'
}
# 地理信息解析
def amp_geocode(addr=None):
url = "https://restapi.amap.com/v3/geocode/geo?parameters"
params = {"key": ak,
"address": addr}
response = requests.get(url, params=params, headers=headers)
if response.status_code == 200:
try:
loc_info = response.json()["geocodes"][0]["location"]
lng = loc_info.split(",")[0]
lat = loc_info.split(",")[1]
print(loc_info)
time.sleep(0.25)
return (lng, lat)
except Exception as e:
print("Exception in amp_geocode",e)
time.sleep(5)
return None
else:
print("========>", response.status_code)
time.sleep(5)
return None
注意事項:
- 訪問API的方式要對,POST、GET方式各有不同,參數要正確
- 網絡訪問,難免會出現錯誤,需要進行異常處理,try…except,此外如果出現短時間出現頻繁的訪問接口,可能百度的服務器會中斷響應,因此如果出現異常時,先讓程序休眠等待一下,即time.sleep(5)
- 對百度地圖訪問量很大的話,可以申請開發者個人認證,百度對認證過的用戶,開放的接口訪問額度大很多。