Google Maps API的使用


之前在學習了簡單的API調用后,查看了幾個知名網站的API調用方法,發現Google的API調用還是相對比較簡單的。下面就從API key的獲取、googlemaps的安裝,再到實際使用做一下說明。
 
1.基於Python的Google MAPS服務:
Google目前在Maps方面開放的API有好幾個,可以根據不同的需求進行使用:
 
2.系統需求:
Python 2.7及以上;
Google MAP API key
 
1) 訪問Google控制台並登陸;

 

2) 點擊左上角的項目進行選擇或者創建新項目:
這里我選擇了之前創建過的項目,可以點擊+號新建
 
3) 點擊"啟用API和服務"開啟你需要的API;

這里選擇跟地圖相關的API:
 

點擊啟用。
顯示此界面就說明啟用成功。
 
4) 創建API key;
點擊左側邊欄中的"憑據"進行創建:

 

5) 限制訪問IP(可選)
點擊后面的修改按鈕可以對密鑰進行IP等設置:

 

4.安裝googlemaps:
C:\Users\DEV>pip install -U googlemaps
Collecting googlemaps
  Downloading googlemaps-2.5.1.tar.gz
Collecting requests<3.0,>=2.11.1 (from googlemaps)
  Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
    100% |████████████████████████████████| 92kB 112kB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 121kB/s
Collecting idna<2.7,>=2.5 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
    100% |████████████████████████████████| 61kB 123kB/s
Collecting certifi>=2017.4.17 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading certifi-2018.1.18-py2.py3-none-any.whl (151kB)
    100% |████████████████████████████████| 153kB 326kB/s
Collecting urllib3<1.23,>=1.21.1 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
    100% |████████████████████████████████| 133kB 216kB/s
Building wheels for collected packages: googlemaps
  Running setup.py bdist_wheel for googlemaps ... done
  Stored in directory: C:\Users\DEV\AppData\Local\pip\Cache\wheels\04\e8\d1\ae5577b5339873e6a5dd55141d56e507cf281b137ef0
9ba924
Successfully built googlemaps
Installing collected packages: chardet, idna, certifi, urllib3, requests, googlemaps
  Found existing installation: chardet 3.0.3
    Uninstalling chardet-3.0.3:
      Successfully uninstalled chardet-3.0.3
  Found existing installation: idna 2.5
    Uninstalling idna-2.5:
      Successfully uninstalled idna-2.5
  Found existing installation: requests 2.14.2
    Uninstalling requests-2.14.2:
      Successfully uninstalled requests-2.14.2
Successfully installed certifi-2018.1.18 chardet-3.0.4 googlemaps-2.5.1 idna-2.6 requests-2.18.4 urllib3-1.22
 
 
執行完上述操作后,我們就可以調用這些API來獲取我們需要的數據了,先使用文檔中的一個例子來調用試試:
import googlemaps from datetime import datetime gmaps = googlemaps.Client(key='Add Your Key here') # Geocoding an address
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA') print(geocode_result[0]['geometry']['location']) # Look up an address with reverse geocoding
reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452)) print(reverse_geocode_result[0]['address_components'][1]['long_name'])
 
上述例子調用了geocode API,並分別打印各自的返回值。
geocode()即地理編碼,根據地址以json格式返回經緯度。
reverse_geocode()即反向地理編碼,根據經緯度返回具體地址。
 
實際調用后,在API首頁便可以看到調用的具體情況。
下面針對directions API進行進一步研究。
 
Directions API
Directions API可以用來計算兩地點之間的路線,並可設置路徑點及出行模式(公交、駕車、騎行、步行等)
先來看一個簡單的調用例子,並分析返回的json數據的具體內容。
import googlemaps from datetime import datetime gmaps = googlemaps.Client(key='Add Your Key here') # Request directions via public transit
now = datetime.now() directions_result = gmaps.directions("Sydney Town Hall", "Parramatta, NSW", mode="transit", departure_time=now) print(directions_result)
例子中gmaps.directions()函數的形參分別為:
起始地點(Sydney Town Hall), 目標地點(Parramatta, NSW), 出行模式(公交), 出發時間(即刻觸發)
然后再來看看根據這個請求返回的數據:
第一次看時有點發暈,這么多數據啊,怎么這么復雜,該怎么搞?其實像這樣將數據格式化后再分析,就比較清楚了。
'legs'中為具體的路徑信息,總體結構如下:
legs: [{
    'arrival_time': {},     # 到達時間
    'departure_time': {},     # 出發時間(這兩個時間在調用時只能指定一個,另一個通過路線規划進行預估)
    'distance': {},     # 兩個地點之間基於路線的距離
    'duration': {},     # 需要花費的時間
    'end_address': '',     # 目的地地址
    'end_location': {},     # 目的地經緯度
    'start_address': {},     # 出發地地址
    'start_location': {},     # 出發地經緯度
    'steps': {},     # 具體的規划路線
    'traffic_speed_entry': [],
    'via_waypoint': []
}]
 
而在'steps'中,又細分為幾段詳細的路線(每一段的信息都在列表的字典元素中),並在每一步中給出了'html_instructions'指示信息,內容非常全:
steps: [
        {
            'distance':     # 第一段路線數據
            'duration':
            'end_location':
            'html_instructions':
            'polyline':
            'start_location':
            'steps': [     # 第一段路線的詳細路徑
                    {
                        'distance': {},     # 
                        'duration':
                        'end_location':
                        'html_instructions':
                        'polyline':
                        'start_location':
                        'travel_mode':
                    },
                    {
                        'distance': {},
                        ... ...
                    },
                    ... ...
                ],
            'travel_mode': ''
        },
        {
            'distance':     # 第二段路線數據
            ... ...
        },
        ... ...
]
可以看到實際返回的數據還是挺復雜的,但是也是非常詳細,想要的數據基本上都在里面了。
 
單純的獲取這些零散數據是沒有什么實際意義的,如果我們能基於現有的數據,或者用爬取的數據與API相結合,就能進行數據分析,並進一步得到一些結論。
根據經緯度值,讓我聯想到可以利用已有的出租車數據集,使用經緯度獲取出租車的位置,並進行分析。
幾個可用的數據集:
下面的數據使用的是Microsoft的T-Drive trajectory data數據(該數據集是由很多個.txt文件組成的,我在使用前先轉換成了csv格式的文件)。
 
根據經緯度,從API獲取兩個節點開車所需的時間及距離,並作出圖表,查看開車時間及距離各自所占的比重。
由於API的調用限制,我們先取前2000條的記錄進行分析:
import googlemaps from datetime import datetime import os import csv import pandas as pd import matplotlib.pyplot as plt import math # 將已知的多個txt文件中的內容放到一個CSV文件下
def txt2Csv(dataPath, csvname): fileList = os.listdir(dataPath) csvFile = open(dataPath + '\\' + csvname, 'w+') writer = csv.writer(csvFile) for fileName in fileList: with open(dataPath + '\\' + fileName) as fileObj: lines = fileObj.readlines() for line in lines: line = line.split(',') line[-1] = line[-1][0:-1] writer.writerow((line)) csvFile.close() # 根據經緯度獲取兩地之間的距離及花費的時間
def getDistanceDuration(key, path, csvName): gmaps = googlemaps.Client(key=key) df = pd.read_csv(path + '\\' + csvName) df.columns = ['id', 'time', 'longitude', 'latitude'] durationList = [] distanceList = [] try: for i in range(1, 1000): now = datetime.now() # 調取google API的directions:
            directions_result = gmaps.directions((df.iloc[i, 3], df.iloc[i, 2]), (df.iloc[i+1, 3], df.iloc[i+1, 2]), mode="driving", departure_time=now) # 按照返回的格式,找出distance及duration,追加到列表中並返回
            distanceList.append(directions_result[0]['legs'][0]['distance']['value']) durationList.append(directions_result[0]['legs'][0]['duration']['value']) except googlemaps.exceptions._RetriableRequest: pass
    return distanceList, durationList path = 'D:\\Learnning\\python\\scrape\\taxiData\\T-drive Taxi Trajectories\\release\\taxi_log_2008_by_id' txt2Csv(path, 'geodata.csv') distanceList, durationList = getDistanceDuration('AIzaSyD8X6tJx6Ap5TVHlqwSso8iTwZfDWcFsOA', path, 'geodata.csv') # 對返回數據的單位做轉換, 並使用math.ceil對數據向上取整
distanceList = [math.ceil(dis/1000) for dis in distanceList] durationList = [math.ceil(dis/60) for dis in durationList] totalDistance = 0 totalDuration = 0 # 計算總路程,並畫出每段路程的距離在總路程中的占比:
for distance in distanceList: totalDistance += distance distancePropo = [distance/totalDistance for distance in distanceList] plt.bar(distanceList, distancePropo) plt.title("Distance interval") plt.xlabel("Km") plt.ylabel("Proportion") plt.show() # 計算總時間,並畫出每段路程花費的時間在總時間中的占比:
for duration in durationList: totalDuration += duration durationPropo = [duration/totalDuration for duration in durationList] plt.bar(durationList, durationPropo) plt.title("Time interval") plt.xlabel("Min") plt.ylabel("Proportion") plt.show()
View Code

 

得出的圖像:
 
按時間分布:
 

 按行駛距離分布:

 

具體的使用文檔可參考:
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM