Use google maps API to calculate distance between lat-longs in a pandas dataframe

  google-maps, pandas, python

I have a pandas dataframe, the snippet of which looks like this:

test
latitude   longitude
17.355282  99.149210
17.355282  99.149210
17.355377  99.149220
17.355377  99.149220
17.355300  99.149280
17.355389  99.149254

I wish to have a new column, say, ‘distance’ which calculates distance between each successive entry using googlemaps API in python.

I have written a function like this:

def calculate_distance(lat1, lon1, lat2, lon2):

    distance = gmaps.distance_matrix([str(lat1) + " " + str(lon1)], 
                                 [str(lat2) + " " + str(lon2)], 
                                 mode='walking')['rows'][0]['elements'][0]['distance']['text'].split(' ')[0]
    return distance

When I called this function:

calculate_distance(test.latitude.values, test.longitude.values,
                 test.loc[1:, 'latitude'].values, test.loc[1:, 'longitude'].values)

I get this response:

{'status': 'NOT_FOUND'}

I also added a shift function to my first lat-long upon calling the function as folows:

calculate_distance(test.latitude.shift(), test.longitude.shift(),
                 test.loc[1:, 'latitude'].values, test.loc[1:, 'longitude'].values)

It puts nan value in the first entry and it gives the following KeyError:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-199-8da29743b4a6> in <module>
      1 calculate_distance(test.latitude.shift(), test.longitude.shift(),
----> 2                  test.loc[1:, 'latitude'].values, test.loc[1:, 'longitude'].values)

<ipython-input-198-64f14b39eec4> in calculate_distance(lat1, lon1, lat2, lon2)
     11     distance = gmaps.distance_matrix([str(lat1) + " " + str(lon1)], 
     12                                  [str(lat2) + " " + str(lon2)],
---> 13                                  mode='walking')['rows'][0]['elements'][0]['distance']['text'].split(' ')[0]
     14     return distance
     15 

KeyError: 'distance'

I verified the API, its working using the first two lat longs:

distance = gmaps.distance_matrix([str(17.355282) + " " + str(99.14921)], 
                                 [str(17.355282) + " " + str(99.149210)], 
                                 mode='walking')['rows'][0]['elements'][0]['distance']['text']

distance
'1 m'

What went wrong here? Appreciate any help.

Thanks

Source: Python Questions

LEAVE A COMMENT