Created
February 17, 2010 18:14
-
-
Save wyattdanger/306870 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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