Last active
May 27, 2019 14:48
-
-
Save sujinleeme/358c271bb92dd2574048fa7e9f46e350 to your computer and use it in GitHub Desktop.
Find the nearest coordinate from a set of geographical coordinates using haversine
This file contains 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
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