【问题标题】:Python Google Map Distance Matrix use only acceptable Zip CodesPython Google Map Distance Matrix 仅使用可接受的邮政编码
【发布时间】:2020-07-08 08:42:16
【问题描述】:

我使用 google 距离矩阵来确定邮编之间的距离,但是,由于数据的性质,有时没有将合法的邮编传递给 API。谷歌仍然返回一个距离。例如,它通过“BLVD”作为邮政编码,它返回 3000 英里。如果不是真正的 zip,我如何告诉 google 的 api 抛出错误?我找不到任何关于它的文档......有什么帮助!谢谢!

url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={}&destinations={}&key={}"

# Get method of requests module
# return response object
r = requests.get(url.format(origin, dest, api_key))

# json method of response object
# return json format result
x = r.json()

如果将 BLVD 传递给它,则 JSON 返回是

{'destination_addresses': ['205 SE Washington Blvd, Bartlesville, OK 74006, USA'], 
'origin_addresses': ['Eagle Mountain, UT 84043, USA'], 
'rows': [{'elements': [{'distance': {'text': '1,150 mi', 'value': 1850562},
'duration': {'text': '17 hours 25 mins', 'value': 62709}, 'status': 'OK'}]}], 
'status': 'OK'}

如果传递了真正的 zip,则 JSON 返回是

{'destination_addresses': ['Salt Lake City, UT 84116, USA'], 
'origin_addresses': ['Eagle Mountain, UT 84043, USA'], 
'rows': [{'elements': [{'distance': {'text': '42.4 mi', 'value': 68169}, 
'duration': {'text': '58 mins', 'value': 3496}, 'status': 'OK'}]}], 
'status': 'OK'}

【问题讨论】:

  • 如果可能的话,你能显示所有从谷歌返回的 json 吗?我认为 api 返回“状态正常”或其他一些消息。
  • 嘿 shimo,我添加了 json 返回。看起来结构是一样的,状态 OK 无论如何都会传回
  • 感谢您的更新。似乎当您搜索 BLVD 作为邮政编码时,距离矩阵 API 将其用作 address。当我阅读API guide 时,他们的搜索参数是地址、经度/纬度或其他,但不是邮政编码。因此,将邮政编码转换为某个地址可能会起作用。

标签: python google-api google-distancematrix-api


【解决方案1】:

感谢您的帮助!由于 Google API 没有任何指示是否真正的 zip 决定创建我自己的函数来验证它是一个 zip。另一种可能性是使用 https://pypi.org/project/zipcodes/ 带有函数 is_real()。

isZip 检查是否至少有 5 或 10 位数字(对于带有连字符的 zip),并确保每个字符都不是字母

def isZip(zipcode):
   if len(zipcode) != 5 and len(zipcode) != 10:
       return False
   for i in zipcode:
       if i.isalpha() is True:
           return False

   return True


lzipcodes = ["90451", "BLVD", "54335-4555"] * 100

for zipcode in lzipcodes:

   print(isZip(zipcode))

【讨论】:

    猜你喜欢
    • 2011-01-07
    • 2017-03-31
    • 2019-10-04
    • 2017-09-18
    • 2022-12-01
    • 1970-01-01
    • 2012-07-13
    • 2017-01-16
    • 2020-01-27
    相关资源
    最近更新 更多