How to find the location closest location in (lat, long) that is closes to the given (lat, long) position with JavaScript?

Sometimes, we want to find the location closest location in (lat, long) that is closes to the given (lat, long) position with JavaScript.

In this article, we’ll look at how to find the location closest location in (lat, long) that is closes to the given (lat, long) position with JavaScript.

How to find the location closest location in (lat, long) that is closes to the given (lat, long) position with JavaScript?

To find the location closest location in (lat, long) that is closes to the given (lat, long) position with JavaScript, we can use the Haversine function.

For instance, we write:

const deg2rad = (deg) => {
  return deg * (Math.PI / 180)
}

const getDistanceFromLatLonInKm = (lat1, lon1, lat2, lon2) => {
  const R = 6371;
  const dLat = deg2rad(lat2 - lat1);
  const dLon = deg2rad(lon2 - lon1);
  const a =
    Math.sin(dLat / 2) ** 2 +
    (Math.cos(deg2rad(lat1)) ** 2) *
    (Math.sin(dLon / 2) ** 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const d = R * c;
  return d;
}

const cities = [
  ["city1", 10, 50],
  ["city2", 40, 60],
  ["city3", 25, 10],
  ["city4", 2, 2]
];

const [closestCity] = cities.sort((c1, c2) => {
  const [, lat1, lon1] = c1
  const [, lat2, lon2] = c2
  return getDistanceFromLatLonInKm(0, 0, lat1, lon1) - getDistanceFromLatLonInKm(0, 0, lat2, lon2)
})
console.log(closestCity)

We define the deg2rad function to convert degrees to radians.

Then we define the getDistanceFromLatLonInKm to calculate the distance between 2 locations with the Haversine function.

We convert the latitude and longitude differences to radians.

Then we calculate a with the latitude, latitude difference and longitude difference with part of the Haversine formula.

Next, we calculate c with a, which is another part of the Haversine formula.

And then we put them together with R * c and returning it.

Then we sort the cities array by the distance closest to (0, 0) with sort and get the closest one with destructuring.

Therefore, closestCity is ['city4', 2, 2].

Conclusion

To find the location closest location in (lat, long) that is closes to the given (lat, long) position with JavaScript, we can use the Haversine function.