I’m new to Python and working with APIs, and I’ve been struggling with an issue while using the Google Maps API to calculate distances between multiple origin and destination points from .cvs coordinates data source files. This is my first time working with Python and APIs, so the problem might be basic, but I’ve been stuck for a while and would appreciate any help.
When I run my code, get the following error:
Error with Google Maps API: 'distance'
Distances for destination (43.3713, -8.4188): [inf, inf, inf, inf, inf]
It seems like the ‘distance’ key is missing from the API response, and I’m not sure why.
Here’s the API I’m using:
results = []
for dest in destinations_coords:
distances = []
for orig in origins_coords:
try:
distance_result = gmaps.distance_matrix(orig, dest, mode='driving')
distance = distance_result['rows'][0]['elements'][0]['distance']['value']
distances.append(distance)
except Exception as e:
print(f"Error with Google Maps API: {e}")
distances.append(float('inf'))
print(f"Distances for destination {dest}: {distances}")
if distances:
nearest_origin_index = distances.index(min(distances))
nearest_origin = origins.iloc[nearest_origin_index]
results.append({
'destination': dest,
'nearest_origin': (nearest_origin['latitud'], nearest_origin['longitud']),
'distance': min(distances)
})
else:
print(f"No distances calculated for destination {dest}")
return results
The CSV files (origenes.csv and provincias.csv) contain three columns: nombre, latitud, and longitud in the following format:
origins.csv
nombre,latitud,longitud
Rockwool,4.236937,-1.65271
Isover,4.05598,-3.2609
Kanuf,4.132636,2.04171
...
provincias.csv
nombre,latitud,longitud
A Coruña,43.3713,-8.4188
Álava,42.8494,-2.6727
Albacete,38.9942,-1.8585
Alicante,38.3452,-0.481
Almería,36.8381,-2.4597
Asturias,43.3614,-5.8593
Ávila,40.6566,-4.7009
Badajoz,38.8794,-6.9706
...
I’ve tried:
Verified that my Google Maps API key is correct and has necessary permissions.
Ensured the coordinates in the CSV files are valid.
Added logging to print the full API response for debugging.
Could someone help me understand why the ‘distance’ key might be missing and how to correctly handle the API responses? Any guidance or pointers would be greatly appreciated!
Thank you!
Fernando Flores is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.