簡體   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