首先在Baidu地圖開發者平臺http://lbsyun.baidu.com/apiconsole/key建立一個本身的應用。本次咱們主要運用的服務是「地理編碼」,即將結構化地址數據轉換爲對應座標點(經緯度),默認轉化出的座標格式是BD-09。編程
http://api.map.baidu.com/geocoding/v3/?address=北京市海淀區上地十街10號&output=json&ak=您的ak&callback=showLocation //GET請求
3.1 訪問本身拼成的url接口,得到返回json格式的數據json
注意:這邊url不可用str類型拼接,否則生成的url是無效的,沒法訪問api
1 def getGPS(addr): 2 data1 = { 3 "address":addr 4 } 5 data2 = { 6 'output':'json', 7 'ak':ak 8 } 9 query_string1 = urllib.parse.urlencode(data1) 10 query_string2 = urllib.parse.urlencode(data2) 11 getUrl = url + '?' + query_string1 + '&' + query_string2 12 result = (json.loads(requests.get(getUrl).text)["result"])["location"] # {'lng': 112.5624746369245, 'lat': 37.89936726508969} 13 14 lng = result["lng"] 15 lat = result["lat"] 16 return(lng ,lat)
3.2 讀寫excel數據編碼
這邊用到openpyxl和xlrd庫,分別用來寫和讀操做url
個人表格格式,最後兩列爲生成的座標經緯度spa
1 def ReadWriteExcel(): 2 workbook = openpyxl.load_workbook(file) 3 worksheet = workbook.worksheets[1] 4 for i in range(1,len(cols1)): 5 location = sheet1.row_values(i)[1:5] 6 str_location = "山西省"+location[2]+location[3]+location[1] 7 lng,lat = getGPS(str_location) 8 9 worksheet.cell(i+1, 9, lng) 10 worksheet.cell(i+1, 10, lat) 11 12 workbook.save(filename="distance.xlsx")
1 # encoding:utf-8 2 import openpyxl 3 import requests 4 import urllib.parse 5 import json 6 import xlrd 7 8 file = 'distance.xlsx' 9 10 url = 'http://api.map.baidu.com/geocoding/v3/' 11 12 ak = "XXXXXXXX" 13 14 wb = xlrd.open_workbook(filename=file) # 打開文件 15 sheet1 = wb.sheet_by_index(1) # 經過索引獲取表格 16 cols1 = sheet1.col_values(1) # 獲取列內容 len(cols1) 17 18 19 def getGPS(addr): 20 data1 = { 21 "address":addr 22 } 23 data2 = { 24 'output':'json', 25 'ak':ak 26 } 27 query_string1 = urllib.parse.urlencode(data1) 28 query_string2 = urllib.parse.urlencode(data2) 29 getUrl = url + '?' + query_string1 + '&' + query_string2 30 result = (json.loads(requests.get(getUrl).text)["result"])["location"] # {'lng': XX.XXXXXXXXXXX, 'lat': XX.XXXXXXXXXXXXXX} 31 32 lng = result["lng"] 33 lat = result["lat"] 34 return(lng ,lat) 35 36 def ReadWriteExcel(): 37 workbook = openpyxl.load_workbook(file) 38 worksheet = workbook.worksheets[1] 39 for i in range(1,len(cols1)): 40 location = sheet1.row_values(i)[1:5] 41 str_location = "XX省"+location[2]+location[3]+location[1] 42 lng,lat = getGPS(str_location) 43 44 worksheet.cell(i+1, 9, lng) 45 worksheet.cell(i+1, 10, lat) 46 47 workbook.save(filename="distance.xlsx") 48 49 50 ReadWriteExcel()
(其中須要根據不一樣的表格格式進行修改)excel