ynnad
ynnad

Reputation: 73

How to Loop Over a list of addresses for Longitude and Latitude (Python)

I'm trying to loop over a list of addresses that I have (Street Name, City, State, Zipcode) in order to get longitudes and latitudes

    for address in addresses:
          g = geolocator.geocode(address)
          print(g.address)
          print((g.latitude, g.longitude))
          LatLong.append((g.latitude, g.longitude))

When I run this code I receive the long and lat for the first address in the list but then get this :

AttributeError: 'NoneType' object has no attribute 'address'

Would greatly appreciate any help.

Upvotes: 0

Views: 2176

Answers (2)

smac89
smac89

Reputation: 43118

Check if g is None before trying to use it:

for address in addresses:
  g = geolocator.geocode(address)

  if g is None:
    print ('{} could not be geocoded'.format(address))
  else:
    print(g.address)
    print((g.latitude, g.longitude))
    LatLong.append((g.latitude, g.longitude))

Upvotes: 0

Dan
Dan

Reputation: 10786

At least some of the geolocators in geopy return None when there are no results found, as indicated in the documentation. You must check the return value before assuming that a result was returned.

Upvotes: 1

Related Questions