sujinleeme
5/21/2019 - 1:39 PM

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

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]
}