Skip to content

Instantly share code, notes, and snippets.

@bitwalker
Last active December 31, 2015 04:49
Show Gist options
  • Save bitwalker/7936925 to your computer and use it in GitHub Desktop.
Save bitwalker/7936925 to your computer and use it in GitHub Desktop.
Need to determine if two physical points on a map are within a certain number of statute miles of each other? I got you covered.
function withinRange(sourceLong, sourceLat, targetLong, targetLat, range) {
var nauticalMilesPerStatuteMile = 0.868976;
// Latitude is always the same distance. Divide degrees by 60 to get arcminutes
var milesPerMinLat = 69.047 / 60;
// Distance in miles per arcminute longitude depends on the cosine of the arcminutes of latitude
var milesPerMinLong = (1 * Math.cos(sourceLat)) / nauticalMilesPerStatuteMile;
// Get delta in minutes between source and target longitude, convert to statute miles
var deltaLong = Math.abs((sourceLong * 60) - (targetLong * 60));
// Convert `deltaLong` to statute miles, rounding to 2 decimal places
var deltaLong = Math.round((milesPerMinLong * deltaLong) * 100) / 100;
// Get delta in minutes between source and target latitude, convert to statute miles
var deltaLat = Math.abs((sourceLat * 60) - (targetLat * 60));
// Convert `deltaLat` to statute miles, rounding to 2 decimal places
var deltaLat = Math.round((milesPerMinLat * deltaLat) * 100) / 100;
// Get combined delta of the lat/long pairs by finding the long
// edge of the triangle formed by the intersection of the deltas
// Yay math!: deltaLong**2 + deltaLat**2 == delta**2
var delta = Math.sqrt(Math.pow(deltaLong, 2) + Math.pow(deltaLat, 2));
// Return true if the delta is less than or equal to `range`, else return false
return delta <= range;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment