Calculating the distance between two locations helps companies like Swiggy and Zomato calculate the **delivery time** for an order. If you want to learn how to calculate the distance between two locations by using their latitude and longitude points, this article is for you. In this article, I will take you through a tutorial on calculating the distance between two locations using **Python**.

## How to Calculate Distance Between two Locations?

We can use the **haversine** formula to calculate the distance between two locations. The haversine formula calculates the distance between two latitude and longitude points. This formula is defined as:

**haversine(d/R) = haversine(latitude2- latitude1 + cos(latitude1 * cos(latitude2 * haversine(longitude2 – longitude1)**

In this formula:

- d is the distance between the two points
- r is the radius of the earth
- and haversine is the haversine function defined as:
**haversine(theta) = sin^2(theta/2)**

To calculate the final distance in kilometres, you need to multiply the distance between the two points by the radius of the earth.

## Calculating Distance Between two Locations using Python

I hope you have understood how the haversine formula can be used to calculate the distance between two latitude and longitude points. Now, below is how we can implement the haversine formula to calculate the distance between two latitude and longitude points using Python:

import numpy as np # Set the earth's radius (in kilometers) r = 6371 # Convert degrees to radians def deg_to_rad(degrees): return degrees * (np.pi/180) # Function to calculate the distance between two points # using the haversine formula def distcalculate(lat1, lon1, lat2, lon2): d_lat = deg_to_rad(lat2-lat1) d_lon = deg_to_rad(lon2-lon1) a = np.sin(d_lat/2)**2 + np.cos(deg_to_rad(lat1)) * np.cos(deg_to_rad(lat2)) * np.sin(d_lon/2)**2 c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a)) return r * c

Now let’s calculate the distance between two locations with the function we just defined above:

print(distcalculate(22.745049, 75.892471, 22.765049, 75.912471))

Output: 3.0251492856773803

The above output shows the distance between two locations according to their latitude and longitude points in kilometres.

### Summary

Calculating the distance between two locations helps companies like Swiggy and Zomato calculate the delivery time for an order. We can use the haversine formula to calculate the distance between two locations. I hope you liked this article on calculating the distance between two locations according to their latitude and longitude points using Python. Feel free to ask valuable questions in the comments section below.