The Chirp

Haversine Formula

5/23/2020


I have not posted an article in a while. To get back into writing, I decided I will do some short technical articles for other geo web develpers of the world. Tips and tricks to help along the way and have a record for myself. The first one will be on the Haversine Formula. The Haversine Formula calculates the great circle or spherical distance between two points on a sphere, such as the earth. For web map developers like myself, this formula becomes very useful.

While there are plenty of resources on the internet to figure this out, I thought it would be handy to have my own JavaScript function for this calcuation. Any web map developer should have a function like this ready to go. In some situations people use Turf's distance and users of Leaflet have the built-in distance method but why not have another!

The map below demostrates an example case using the Haversine Formula. Drag the markers to find the distance between them. Result is rounded to the nearest mile.

Haversine Distance: .
Leaflet's map.distance: .

The function I made takes 4 arguments, the long/lat of the first point then the long/lat of the second point. These are all expecting decimal degrees in WGS84. The function turns the decimal degrees to radians, then finds the deltas, then applys these variables to the Haversine Formula itself.


function getDistanceInMiles(ddLng1,ddLat1,ddLng2,ddLat2) {
    function degToRad(deg) {return deg * Math.PI/180;}
    // convert decimal degree coordinates to radians
    var lng1 = degToRad(ddLng1);
    var lat1 = degToRad(ddLat1);
    var lng2 = degToRad(ddLng2);
    var lat2 = degToRad(ddLat2);
    var deltaLat = lat2 - lat1;
    var deltaLng = lng2 - lng1;
    // Haversine Formula
    var R = 3961; //Earth's Radius, Miles = 3961, Kilometers = 6371, Feet = 20914080
    var a = Math.pow(Math.sin(deltaLat/2),2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(deltaLng/2),2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    return d;
}

It is worth reminding, the earth is lumpy and not a perfect sphere and the Haversine Formula is based on the spherical model of the earth. As for the accuracy of the formula, I have tested it at close distances in Pennsylvania vs. projected GIS data and it is usually accurate within a foot or two. Note that the 'R' value, Earth's radius, changes depending on your position on the globe. This can be adjusted for your region where your measurements will happen most often. Keep this in mind as you determine if this function is right for you.