get nearest location based on latitude and longitude javascript

Get Nearest Location Based on Latitude and Longitude in Javascript

As a blogger who loves traveling, I have often found myself in situations where I need to find the nearest location based on my current latitude and longitude. In such cases, there are a few different ways to achieve this using Javascript.

Option 1: Haversine Formula

The Haversine Formula is a commonly used formula for calculating the distance between two points on a sphere. In Javascript, we can use this formula to calculate the distance between our current location and all available locations, and then sort them by distance to find the nearest location.


function distance(lat1, lon1, lat2, lon2) {
  const R = 6371; // Radius of the earth in km
  const dLat = toRadians(lat2-lat1);
  const dLon = toRadians(lon2-lon1); 
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(toRadians(lat1)) * Math.cos(toRadians(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;
}

function toRadians(degrees) {
  return degrees * Math.PI / 180;
}

function getNearestLocation(lat, lon, locations) {
  const distances = [];
  for (let i = 0; i < locations.length; i++) {
    const loc = locations[i];
    distances.push({
      index: i,
      distance: distance(lat, lon, loc.lat, loc.lon),
    });
  }
  distances.sort((a, b) => a.distance - b.distance);
  return locations[distances[0].index];
}

In the code above, we define a function called `distance` which calculates the distance between two points using the Haversine Formula. We also define a function called `getNearestLocation` which takes in our current latitude and longitude, as well as an array of available locations. This function loops through all available locations, calculates the distance between each location and our current location, and then sorts them by distance. Finally, we return the location with the shortest distance.

Option 2: Geolocation API

If we have access to the user's browser's Geolocation API, we can use it to get their current location and then calculate the distance between their location and all available locations. This approach can be more accurate, as it takes into account factors such as traffic and road closures.


function getNearestLocation(locations) {
  navigator.geolocation.getCurrentPosition(position => {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const distances = [];
    for (let i = 0; i < locations.length; i++) {
      const loc = locations[i];
      distances.push({
        index: i,
        distance: distance(lat, lon, loc.lat, loc.lon),
      });
    }
    distances.sort((a, b) => a.distance - b.distance);
    return locations[distances[0].index];
  });
}

In the code above, we define a function called `getNearestLocation` which takes in an array of available locations. Inside this function, we use the browser's Geolocation API to get the user's current latitude and longitude. We then loop through all available locations, calculate the distance between each location and the user's location, and sort them by distance. Finally, we return the location with the shortest distance.

Conclusion

Both the Haversine Formula and the Geolocation API are effective ways to find the nearest location based on latitude and longitude in Javascript. The Haversine Formula approach is more suitable if we don't have access to the user's current location, while the Geolocation API approach is more accurate if we do have access to it.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe