2

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

Z.Chen
  • 385
  • 1
  • 3
  • 13

2 Answers2

3

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
Shenan
  • 338
  • 1
  • 6
2

I just had a very similar issue, and tried Shenan's answer. I think it's important to inform, that this code returns information only from the first part of the postal code. In this case, both examples, from the question's author ("A1B 2C3") and the answer's ("A1B C14") returns the exactly same latitudes and longitudes value, and works exactly the same if you use only "A1B" instead.
Please, correct me if I'm wrong, but that's the results I'm getting.

This is where I saw the meaning of each character in Canadian postal code: https://en.wikipedia.org/wiki/Postal_codes_in_Canada

KuroSuzume
  • 94
  • 1
  • 13