繁体   English   中英

Python Google Map 距离矩阵仅使用可接受的 Zip 代码

[英]Python Google Map Distance Matrix use only acceptable Zip Codes

我使用谷歌距离矩阵来确定拉链之间的距离,但是,由于数据的性质,有时没有合法的 zip 代码被传递给 API。 谷歌仍然返回一个距离。 例如,它作为 zip 代码传递“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'}

谢谢您的帮助。 由于谷歌 API 没有任何迹象表明真正的 zip 或没有决定创建我自己的 function 来验证它是一个 zip。 另一种可能性是将https://pypi.org/project/zipcodes/与 function 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM