Skip to content

Instantly share code, notes, and snippets.

@wyattdanger
Created February 17, 2010 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyattdanger/306870 to your computer and use it in GitHub Desktop.
Save wyattdanger/306870 to your computer and use it in GitHub Desktop.
var locations = [[37,-122],[38,-121],[39,-120]], // An array of arrays of [ lat , lng ]. You'll find the closest to target
target = [37.75,-121], // starting point
radians = function (deg) {
return Math.PI*deg/180; // needed function not native to JavaScript's Math object
};
function getDistances (target, locations) {
var spots = [];
for (var i=0;i<locations.length;i++) {
var distance = 0,
loc = locations[i];
with (Math) {
distance = ( 3959 * acos( cos( radians(target[0]) ) * cos( radians( loc[0] ) ) * cos( radians( loc[1] ) - radians(target[1]) ) + sin( radians(target[0]) ) * sin( radians( loc[0] ) ) ) );
}
spots.push({'distance':distance,'points':loc})
}
return spots;
}
function sortSpots (spots) {
return spots.sort(function(prev, next){
return (prev.distance <= next.distance) ? -1 : 1;
});
}
sortSpots(getDistances(target, locations)) // This returns the closest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment