Google Maps距离矩阵API(网络服务)中的出发时间与商业许可

0 投票
1 回答
1690 浏览
提问于 2025-04-18 18:44

我有一个Google地图的商业许可证,但我仍然无法获得包含当前交通时长的响应。下面是我正在使用的Python代码示例。

#! /usr/bin/env python3

import time
import urllib.parse
import base64
import hmac
import hashlib
import urllib.request


# Set variables.
client_id = 'gme-DUMMY'
crypto_key = 'DUMMY'
url_base = 'https://maps.googleapis.com/maps/api/distancematrix/json?'


# Construct URL. ---------------------------------------------------------------
query_args = { 'origins':'2097 Honeysuckle Lane Southwest, Atlanta, GA 30311, USA',
               'destinations':'67 Fitzgerald Street Southeast, Atlanta, GA 30312, USA',
               'client':client_id,
               'departure_time':time.time()  # +2*60 or +5*60 does nothing
         }
encoded_args = urllib.parse.urlencode(query_args)
url = url_base + encoded_args


# Get encoded_signature. -------------------------------------------------------
# Remove the 'https://' from url.
url_parsed = urllib.parse.urlparse(url)
url_to_sign = url_parsed.path + "?" + url_parsed.query

# Decode crypto_key into its binary format.
decoded_key = base64.urlsafe_b64decode(crypto_key)

# Create a signature using HMAC SHA1. This signature will be binary.
signature = hmac.new(decoded_key, url_to_sign.encode('utf-8'), hashlib.sha1)

# Encode the binary signature into base64 for use within a URL.
encoded_signature = base64.urlsafe_b64encode(signature.digest()).decode("utf-8")


# Append encoded_signature to url. ---------------------------------------------
encoded_url = url + '&signature=' + encoded_signature


# Send query. ------------------------------------------------------------------
f = urllib.request.urlopen(encoded_url)
print(f.read().decode('utf-8'))

补充说明:

  • 我尝试在departure_time中加上两分钟和五分钟,但没有任何效果。(文档中只是提到departure_time应该在当前时间的几分钟内。)

  • 我确认代码是有效的,返回的时长和maps.google.com上显示的“没有交通的时长”是一样的。

  • 我在StackOverflow上搜索了几个小时,想找一个提问/回答的人确实有商业许可证,但没找到。如果有,请告诉我。

  • 上面的代码遵循了Google的示例,不过是移植到Python 3.x的。

1 个回答

0

你需要把出发时间转换成协调世界时(UTC)。

query_args = { 'origins':'2097 Honeysuckle Lane Southwest, Atlanta, GA 30311, USA',
           'destinations':'67 Fitzgerald Street Southeast, Atlanta, GA 30312, USA',
           'client':client_id,
           'departure_time':calendar.timegm(time.gmtime())
     } 

撰写回答