Skip to content

Instantly share code, notes, and snippets.

@sujinleeme
Last active May 27, 2019 14:48
Show Gist options
  • Save sujinleeme/358c271bb92dd2574048fa7e9f46e350 to your computer and use it in GitHub Desktop.
Save sujinleeme/358c271bb92dd2574048fa7e9f46e350 to your computer and use it in GitHub Desktop.
Find the nearest coordinate from a set of geographical coordinates using haversine

Find the nearest coordinate from a set of geographical coordinates using haversine

function toRad(num) {
return num * Math.PI / 180;
}
function distance(lat1, lon1, lat2, lon2) {
const R = 6371; // Radius of the earth in km
const dLat = toRad(lat2-lat1); //degrees too radians
const dLon = toRad(lon2-lon1);
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const d = R * c; // Distance in km
return d;
}
export default function nearestPoint(lat, lon, locations) {
const new_locations = locations
.map(e => [...e, { distance: distance(lat, lon, e[1], e[0]) }])
.sort((a, b) => a[2].distance - b[2].distance)
return new_locations[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment