Steffen Steffen - 1 year ago 62
Python Question

Reverse geocode, reading .CSV file and TypeError: a float is required

Fixed: Added float() to coordinates1 and coordinates2:

my_location = gmaps.reverse_geocode(float(coordinates1), float(coordinates2))

I'm trying to convert lat long coordinates to addresses. I have a .CSV file with the coordinates, and I don't know if my code can read it, or if it's something else that's wrong.
Here is my code:

from pygeocoder import Geocoder
import csv

gmaps = Geocoder(api_key='api-key')

input = open('C:/Users/Steffen/PycharmProjects/untitled/sadist.csv','r')
output = open('C:/Users/Steffen/PycharmProjects/untitled/distsaretailer.csv', 'w')

reader = csv.reader(input)
writer = csv.writer(output)

for row in reader:
coordinates1 = row[0]
coordinates2 = row[1]

my_location = gmaps.reverse_geocode(coordinates1,coordinates2)



The error message:

Traceback (most recent call last):
File "C:/../", line 22, in <module>
my_location = gmaps.reverse_geocode(coordinates1,coordinates2)

File "C:\..\", line 155, in reverse_geocode
'latlng': "%f,%f" % (lat, lng),
['69.9687376', '23.2715496']
TypeError: a float is required

Answer Source

As PM 2Ring pointed out, you need to convert the coordinates from strings into floating point numbers. Replace:

coordinates1 = row[0]
coordinates2 = row[1]


coordinates1, coordinates2 = [float(c) for c in row]