# How to calculate the distance between two locations using Haversine Formula? [closed]

I have the columns of Latitude and Longitude of city like shown below :

             City                        Latitude                 Longitude

1) Vauxhall Food & Beer Garden           -0.123684                  51.485020

2) 14 Hills                              -0.129212                  51.507426

3) Cardiby                               -0.123234                  52.476264


Now I want to calculate distance between the coordinates of specific place with all cities as shown in data frame . Like

Lon = 0.1245 Lat = 51.685

These above two coordinates should be subtracted with Lat/Lon cities of DataFrame . Output should look like:

      City                        Latitude                 Longitude            Distance

1) Vauxhall Food & Beer Garden           -0.123684                  51.485020    275km

2) 14 Hills                              -0.129212                  51.507426    856km

3) Cardiby                               -0.123234                  52.476264    584km


My code :

from haversine import haversine

from math import sin, cos, sqrt, atan2, radians

df['Latitude'] = [radians(i) for i in df['Latitude']]
df['Longitude'] = [radians(j) for j in df['Longitude']]

dlon = [i-lat2 for i in df['Latitude']]
dlat = [j-lon2 for j in df['Longitude']]

df['distance']=haversine(df['Latitude'],df['Longitude'],dlat,dlon)

print(df['distance'])


It is not working ,

I am not an expert in geometrics but I found that this function has already been supported by sklearn. So I decided to help you define a generic function.

from sklearn.metrics.pairwise import haversine_distances
import pandas as pd

def distance(location1, lat, lon):
location2 = [lat, lon]
result = result * 6371000/1000  # multiply by Earth radius to get kilometers

return result[0][1]

df = pd.DataFrame({
'Latitude': [-0.123684, -0.129212, -0.123234],
'Longitude': [51.485020, 51.507426, 52.476264]
})

df.apply(lambda x: distance([0.1245, 51.685], x.Latitude, x.Longitude),axis=1)
# 0    35.440884
# 1    34.434944
# 2    92.195943
# dtype: float64