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