Skip to content

Instantly share code, notes, and snippets.

@qubyte
Created May 28, 2013 17:12
Show Gist options
  • Save qubyte/352bcad240402f978bd1 to your computer and use it in GitHub Desktop.
Save qubyte/352bcad240402f978bd1 to your computer and use it in GitHub Desktop.
Haversine formula for stable distance calculation between pairs of coordinates.
// All angles in radians.
function haversine(aLong, aLat, bLong, bLat) {
var R = 6371; // Radius of Earth.
var latDiff = bLat - aLat;
var longDiff = bLong - aLong;
var step1 = Math.sin(latDiff / 2);
var step2 = Math.sin(longDiff / 2);
var step3 = step1 * step1 + step2 * step2 * Math.cos(aLat) * Math.cos(bLat);
var step4 = 2 * Math.atan2(Math.sqrt(step3), Math.sqrt(1 - step3));
return R * step4;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment