Skip to content

Instantly share code, notes, and snippets.

@Thibaut-B
Created October 7, 2015 13:14
Show Gist options
  • Save Thibaut-B/56071bcc8207fa11be90 to your computer and use it in GitHub Desktop.
Save Thibaut-B/56071bcc8207fa11be90 to your computer and use it in GitHub Desktop.
Find the closest location
var cities = [
{
name: 'berlin',
latitude: '52.5167',
longitude: '13.3833',
},
{
name: 'athena',
latitude: '37.9667',
longitude: '23.7167',
}
];
function pythagorasEquirectangular( lat1, lon1, lat2, lon2 ) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2-lon1) * Math.cos((lat1+lat2)/2);
var y = (lat2-lat1);
var d = Math.sqrt(x*x + y*y) * R;
return d;
}
// Convert Degress to Radians
function Deg2Rad( deg ) {
return deg * Math.PI / 180;
}
function nearestCity( latitude, longitude )
{
var mindif=99999;
var closest;
for (index = 0; index < cities.length; ++index) {
var dif = pythagorasEquirectangular(latitude, longitude, cities[index].latitude, cities[index].longitude);
if (dif < mindif) {
closest=index;
mindif = dif;
}
}
return cities[closest];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment