MoreScratch MoreScratch - 2 years ago 120
Python Question

Geopy: catch timeout error

I am using geopy to geocode some addresses and I want to catch the timeout errors and print them out so I can do some quality control on the input. I am putting the geocode request in a try/catch but it's not working. Any ideas on what I need to do?

Here is my code:

location = geolocator.geocode(my_address)
except ValueError as error_message:
print("Error: geocode failed on input %s with message %s"%(a, error_message))

I get the following exception:

File "/usr/local/lib/python2.7/site-packages/geopy/geocoders/", line 158, in _call_geocoder
raise GeocoderTimedOut('Service timed out')
geopy.exc.GeocoderTimedOut: Service timed out

Thank you in advance!

Answer Source

Try this:

from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut

my_address = '1600 Pennsylvania Avenue NW Washington, DC 20500'

geolocator = Nominatim()
    location = geolocator.geocode(my_address)
    print location.latitude, location.longitude
except GeocoderTimedOut as e:
    print("Error: geocode failed on input %s with message %s"%(my_address, e.msg))

You can also consider increasing the timeout on the geocode call you are making to your geolocator. In my example it would be something like:

location = geolocator.geocode(my_address, timeout=10)


location = geolocator.geocode(my_address, timeout=None)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download