Distances Calculation GPS Coordinates Using The Haversine Formula in JavaScript

Photo by henry perks on Unsplash

Distances Calculation GPS Coordinates Using The Haversine Formula in JavaScript

Calculating distances between geographic coordinates is a common problem for location-based apps and services. One of the most accurate methods for this is the haversine formula, which considers the Earth's spherical shape.

In this article, we'll build a JavaScript function to calculate distances between two sets of GPS coordinates using the haversine formula. We'll also explore some practical applications of this and see the formula in action.

So what is the haversine formula? It's a navigation way of calculating great-circle distances between two points on a sphere given their longitudes and latitudes. The "haversine" part refers to haversine(θ) = sin2(θ/2), which shows up in the formula.

The full haversine formula is:

d = 2 r arcsin(√( haversine(Δφ/2) + cos(φ1)cos(φ2) haversine( Δλ/2)))

Where:

• φ1,λ1 are the latitude and longitude of the first point
• φ2,λ2 are the latitude and longitude of the second point
• Δφ = φ2 - φ1
• Δλ = λ2 - λ1
• r is Earth's radius — 6371 km

Essentially, this formula calculates the angle between two points in radians, then multiplies that by Earth's radius to get the distance in kilometers.

Let's see how we could implement this in JavaScript:

function distance(lat1, lon1, lat2, lon2) { // Convert to radians let φ1 = radians(lat1); let φ2 = radians(lat2); let Δλ = radians(lon2 - lon1);

let d = 2 Math.asin(Math.sqrt(haversine(φ1, φ2) + cos(φ1) cos(φ2) * haversine(Δλ)));

// Radius of Earth in kilometers let r = 6371;

return (d * r); }

function haversine(φ1, φ2) { let Δφ = φ2 - φ1; return Math.pow(Math.sin(Δφ/2), 2); }

function radians(degrees) { return degrees * Math.PI/180; }

Now we have a function that can calculate distances between sets of GPS coordinates!

Some practical uses of this include:

  • Finding nearby locations in location-based apps

  • Determining pickup/dropoff distances for rideshare and delivery services

  • Calculating travel times between locations

  • Clustering locations that are "close enough" together

  • Optimizing routes and waypoints for journey planning

The haversine formula provides very high accuracy - around 0.5% error compared to 10-15% error when using a flat Earth approximation. This extra precision is important for any application that deals with location data on a global scale.

So, in summary, the haversine formula gives us an accurate and mathematically elegant way to calculate distances between points on the surface of a sphere - in our case, GPS coordinates on Earth. With a simple JavaScript implementation, we can integrate this capability into our applications to enable features like location search, routing, and recommendation systems.

Did you find this article valuable?

Support Sangya Sherpa by becoming a sponsor. Any amount is appreciated!