Skip to content
the poor coder

get nearest location based on latitude and longitude javascript

Poor Man
Published
Reading time
3 min read
On this page

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.

Text

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC