Rick Cogley's Tech Logr

Short Technical Laser Bursts %%

RC Logr 20190405 182129

Friday, 5 Apr, 2019

You can use the Haversine formula to approximate the «great-circle» distance between points on the globe, to get, say, the distance between map locations expressed in latitude and longitude. 🗺

Haversine Distance Formula

You can see it in use in this javascript around line 247, the meat of which is this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
...
calcDistance: function (loc1, loc2){
  var rad = function(x) {return x*Math.PI/180;}
  var R = 6371; // earth's mean radius in km
  var dLat  = rad(loc2.latitude - loc1.latitude);
  var dLong = rad(loc2.longitude - loc1.longitude);

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(loc1.latitude)) * Math.cos(rad(loc2.latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;

  return d.toFixed(3);
},
...

RC Logr 20190405 182129 - You can use the Haversine … Rick Cogley
Back to Home Tweet Link