Calculating the Distance between Two Locations Using Geocodes | by Francis Adrian Viernes | Towards Data Science

You’ve heard the famous phrase “Location, Location, Location” for instances where people want to emphasize the centrality of the location to business and real estate.
In data analysis and computing, however, this phrase is a bit ambiguous. The way computers understand the concept of “location” is through what we know as “geocodes.” These are the longitudes and latitudes and are specific to a particular location.
Note: For those who want to know how to calculate these geocodes, I have written an article regarding this.
From the geocodes of different locations, we can generate other “features.” This process is an example of geospatial feature engineering.
One particular feature is the distance between an origin and a destination location. Distance plays an important feature for a lot of machine learning problems, for example, customer and employee churn prediction, foot traffic, and in certain cases, wealth prediction.
For example, certain studies indicate that churn probability is higher for employees and customers that are located farther from a point of interest, say a branch or company. But with just geocodes, it is not possible to generate this feature and therefore use them in Machine learning models.
But, how do you compute for the location between a set of longitudes and latitudes?
One way is to use the formula for the Great Circle Distance.
The Great Circle distance, sometimes called Orthodomic, or Spherical distance, is the shortest distance between two points in a sphere.
Although not a perfect sphere, the distance between two points on the surface of the earth can therefore be approximated by the great circle distance.
The formula, given that we have the geocodes, are as follows:
Note that in the formula, the geocodes are assumed to be radians, rather than in degrees. The geocodes that we normally get from the web or through providers such as Google APIs are provided in degrees.
Without further ado, here’s the code to calculate the haversine distance:
import numpy as npdef haversine_distance(lat1, lon1, lat2, lon2):    '''    Calculates the spherical distance between two sets of geocodes coming from an origin and a destination.        Parameters:    --------------    lat1: float         - latitude of the origin location in degrees    lon1: float         - longitude of the origin location in degrees        lat2: float         - latitude of the destination location in degrees    lon2: float         - longitude of the destination location in degrees              Returns:    --------------    Float distance in km.        '''    r = 6371 # radius of the Earth in Km        # Convert degrees to radians      phi1 = np.radians(lat1)    phi2 = np.radians(lat2)        delta_phi = np.radians(lat2 - lat1)    delta_lambda = np.radians(lon2 - lon1)        a = np.sin(delta_phi / 2)**2 + np.cos(phi1) * np.cos(phi2) *   np.sin(delta_lambda / 2)**2        c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))            d = r * c        return f'{d:.2f} KM'
Let’s try out our function:
Try to check out the actual distance from Google Maps and verify that indeed, this is a good approximation.
The Great Circle Distance, or Haversine Distance, approximates the distance between two locations well over short distances.
For longer distances, the approximation fails as more road obstacles, blockages, and ways lengthen the overall pathway.
For this purpose, one can resort to trying the Google API to calculate the total distance between the two points.
See my article regarding Geocoding and accessing the Google Maps API:
Let me know what you think!