使用Python中的google distance matrix API计算两个位置之间的距离和持续时间

谷歌地图距离矩阵API是一项提供旅行距离和到达目的地所需时间的服务。此API返回始发地和目的地之间的推荐路线(未详细说明),该路线由每对的持续时间和距离值组成。

null

要使用此API,必须使用 API密钥 ,可以从表格中获取 在这里 .

所需模块:

import requests
import json

以下是实施情况:

# importing required libraries
import requests, json
# enter your api key here
api_key = 'Your_api_key'
# Take source as input
source = input ()
# Take destination as input
dest = input ()
# url variable store url
# Get method of requests module
# return response object
r = requests.get(url + 'origins = ' + source +
'&destinations = ' + dest +
'&key = ' + api_key)
# json method of response object
# return json format result
x = r.json()
# by default driving mode considered
# print the value of x
print (x)


输出:

dehradun
haridwar

{'destination_addresses': ['Haridwar, Uttarakhand, India'], 
'origin_addresses': ['Dehradun, Uttarakhand, India'], 'rows': 
[{'elements': [{'distance': {'text': '56.3 km', 'value': 56288}, 
'duration': {'text': '1 hour 40 mins', 'value': 5993},
'status': 'OK'}]}], 'status': 'OK'}

使用 googlemaps 模块:

两个地方之间的距离也可以使用 专用码 单元

要安装的命令 专用码 模块:

pip install googlemaps

# importing googlemaps module
import googlemaps
# Requires API key
gmaps = googlemaps.Client(key = 'Your_API_key' )
# Requires cities name
my_dist = gmaps.distance_matrix( 'Delhi' , 'Mumbai' )[ 'rows' ][ 0 ][ 'elements' ][ 0 ]
# Printing the result
print (my_dist)


输出:

{'distance': {'text': '1,415 km', 'value': 1415380}, 'duration': {'text': '23 hours 42 mins', 'value': 85306}, 'status': 'OK'}

幸亏 艾什瓦亚。27 感谢你对这种方法的贡献。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享