Skip to content

Instantly share code, notes, and snippets.

@djom202
Created May 8, 2018 16:45
Show Gist options
  • Save djom202/803b22d4605179c26ceb62afd4cf12eb to your computer and use it in GitHub Desktop.
Save djom202/803b22d4605179c26ceb62afd4cf12eb to your computer and use it in GitHub Desktop.
Using the Haversine Formula in Javascript Ask
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;
var R = 6371; // km
//has a problem with the .toRad() method below.
var x1 = lat2-lat1;
var dLat = x1.toRad();
var x2 = lon2-lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
alert(d);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment