0

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.

Fatema Tuz Zuhora
  • 3,088
  • 1
  • 21
  • 33
ynnad
  • 73
  • 1
  • 6

2 Answers2

1

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.

Dan
  • 10,531
  • 2
  • 36
  • 55
  • Thank you. Reading through the documentation now – ynnad Sep 14 '19 at 06:31
  • When I manually enter addresses that the Geocoder couldn't find during the loop they are located. Any hope of translating that back into the loop? The underlying addresses are all formatted the same – ynnad Sep 14 '19 at 07:01
  • @ynnad Are you sure that you're using the same Geocoder? If you run it through the loop again, does it still fail? Is it possible that there is some small (even invisible) difference between the two strings, such as non-printable characters? – Dan Sep 14 '19 at 17:48
0

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))
smac89
  • 39,374
  • 15
  • 132
  • 179
  • Thank you. This worked for the majority of the addresses. However, the rest did have g = none. (New coder here and I'm not understanding the logic as to why. Where g = none, address are present so why is g = none?) – ynnad Sep 14 '19 at 06:20
  • @ynnad, `g` is none because the geocoder could not locate the address. See the [other answer](https://stackoverflow.com/a/57932658/2089675) – smac89 Sep 14 '19 at 06:21