使用 Python 中的 google distance matrix API 計算兩地之間的距離和持續時間?


我們幾乎都使用 Google 地圖來檢視源地址和目的地之間的距離以及檢視行程時間。對於開發者和愛好者,Google 提供“Google Distance Matrix API”,用於計算兩地之間的距離和持續時間。

要使用 Google Distance Matrix API,我們需要 Google 地圖 API 金鑰,你可以從下方連結獲取

https://developers.google.com/maps/documentation/distance-matrix/get-api-key

所需庫

我們可以使用不同的 Python 庫來實現此功能,例如

  • Pandas
  • googlemaps
  • Requests
  • Json

我使用非常基本的 Requests 和 Json 庫。使用 Pandas,你可以一次填充多個源地址和目的地,並將結果獲取為 csv 檔案。

以下是實現此功能的程式

# Import required library
import requests
import json
#Enter your source and destination city
originPoint = input("Please enter your origin city: ")
destinationPoint= input("Please enter your destination city: ")
#Place your google map API_KEY to a variable
apiKey = 'YOUR_API_KEY'
#Store google maps api url in a variable
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
# call get method of request module and store respose object
r = requests.get(url + 'origins = ' + originPoint + '&destinations = ' + destinationPoint + '&key = ' + apiKey)
#Get json format result from the above response object
res = r.json()
#print the value of res
print(res)

輸出

Please enter your origin city: Delhi
Please enter your destination city: Karnataka
{'destination_addresses': [‘Karnataka, India’],'origin_addresses': [‘Delhi, India’], 'rows': [{'elements': [{'distance': {'text': '1,942 km', 'value': 1941907}, 'duration': {'text': '1 day 9 hours', 'value': 120420},
'status': 'OK'}]}], 'status': 'OK'}

更新於: 2019 年 7 月 30 日

652 次瀏覽

開啟你的職業生涯

完成課程認證

開始學習
廣告
© . All rights reserved.