Reputation: 107
I wanted to make a program where you enter your address(the example in the code is a Dutch address) and then the program gives as output the longitude and the latitude od that address. I also tried to make it more user-friendly so if the entered address doesn't exist, the program will say that. the code is:
from geopy.geocoders import ArcGIS
nom = ArcGIS()
adres = input("enter your adress as folows:\n 32 Gunterstein, Amsterdam, 1081 CJ\n vul in: ")
n = nom.geocode(adres)
if adres in nom:
print("longitude:",n.longitude)
print("latitude:", n.latitude)
else:
print("adress doesn't exist, please try again.")
print("end")
if the user enters a valid address the code works but when I try that out by entering nonsense I get the following error:
enter your adress as folows:
32 Gunterstein, Amsterdam, 1081 CJ
vul in: nonsense
Traceback (most recent call last):
File "breede_en_lengte_graden.py", line 7, in <module>
if adres in nom:
TypeError: argument of type 'ArcGIS' is not iterable
What is wrong with the code that I get that error?
Thanks!
Upvotes: 0
Views: 226
Reputation: 5723
I don't think it throws an error on erroneous address.
n = nom.geocode('sdf324uio')
n is None
True
Just check if n
is None
to see if a valid address was passed to it.
Edit:
It's funny that actually nonsense
exists as place and it returns a valid location (it was my first attempt for a non-existing address):
n = nom.geocode('nonsense')
n
Location(Nonsense, (-23.56400999999994, -46.66579999999993, 0.0))
Upvotes: 0
Reputation: 24068
This is one way of doing it with a try-except
block:
try:
print("longitude:", n.longitude)
print("latitude:", n.latitude)
except AttributeError:
print("adress doesn't exist, please try again.")
print("end")
You can also do it with an if-else
block, but you'll have to do it little bit differently:
if n is not None:
print("longitude:", n.longitude)
print("latitude:", n.latitude)
else:
print("adress doesn't exist, please try again.")
print("end")
The reason for this kind of checking is that the nom.geocode(adres)
doesn't fail on invalid addresses, instead it simply returns None
and that is assigned to be the value of n
.
Upvotes: 1