geopy wont return proper coordinates for canadian postal codes

Tags: , ,



I am trying to convert Canadian Postal codes into lat, long coordinates however geopy returns them as either none or somewhere in a different country

postal_code = "A1B 2C3" #<-- in this format
location = geolocator.geocode(postal_code)

print(location.latitude, location.longitude)

Output AttributeError: 'NoneType' object has no attribute 'latitude' OR some random address

Answer

I think the problem here is either the API you use for geopy does not support for CA zip code, or you don’t set ‘CA’ as the country option. So when the geocode can’t retrieve the info from the input, it returns None.

To achieve the same goal, I would prefer use pgeocode library.

import pgeocode
nomi = pgeocode.Nominatim('ca')
postal_code = "A1B C14"
location = nomi.query_postal_code(postal_code)
print(location.latitude, location.longitude)
47.5698 -52.7796


Source: stackoverflow