0

I am using the google distance matrix to determine the distance between zips, however, with the nature of the data sometimes there is not a legitimate zip code being passed to the API. Google still returns a distance. For example it was passed "BLVD" as the zip code and it returned 3000 miles. How can i tell google's api to throw an error if its not a real zip? I couldn't find any documentation on it...anything helps! thank you!

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()

If BLVD is passed to it the JSON return is

{'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'}

and if a real zip is passed JSON return is

{'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'}
Josh Pachner
  • 151
  • 6
  • If possible, can you show all of the returned json from Google? I think api returns "status ok" or some other messages. – shimo Jul 06 '20 at 23:03
  • hey shimo, i added the json returns. It appears the structure is the same, and status OK is passed back regardless – Josh Pachner Jul 07 '20 at 18:18
  • Thank you for update. It seems that when you search BLVD as a zip code Distance Matrix API use it as *address*. As I read the [API guide](https://developers.google.com/maps/documentation/distance-matrix/intro), their search parameters are address, longitude/latitude or else but not zip code. So converting zip code to some address may work. – shimo Jul 07 '20 at 22:42

1 Answers1

0

thanks for the help! Since Google API has nothing to indicate if real zip or not decided to create my own function to verify that it is a zip. Another possibility was to use the https://pypi.org/project/zipcodes/ with the function is_real().

isZip checks to see if at least 5 or 10 digits long(for the zips with the hyphen) and makes sure every character is not an alpha

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))
Josh Pachner
  • 151
  • 6