Create Distance Matrix API using Math & JavaScript

Create Distance Matrix API using Math & JavaScript

I published a Distance Matrix NPM Package which calculates the shortest distance from the user's location, why'd I pay Google for that?

ยท

2 min read

While working on my project, I was faced with the challenge of determining the nearest restaurant to the user's location. This was a crucial aspect of ensuring that food orders could be delivered quickly to the customer's doorstep. Fortunately, a friend introduced me to the Haversine Formula. This formula is used to calculate the distance between two points on a sphere or circle based on their latitude and longitude coordinates.

Instead of relying on expensive API-as-a-Service options like Google Maps, I decided to create my package called 'short-distance'. This package utilizes the Haversine Formula to calculate the distance between two points and returns the nearest location from the starting point to the user-provided locations. By building this functionality into my project, I was able to provide a more streamlined and cost-effective solution for determining the nearest restaurant to the user's location.

Usage

To begin using the 'short-distance' package in your project, you first need to install it as a dependency. This can be done using either the npm or yarn package managers.

The 'short-distance' package is lightweight and has no dependencies on any other packages, which ensures optimal performance. Installing the package is a simple process, as shown below:

npm i short-distance
// or yarn add short-distance

Once the package is installed, you can begin using its functionality in your project to calculate the shortest distance between two points based on their latitude and longitude coordinates.

const shortestDistance = require('short-distance');

const startingPoint = {
  latitude: 37.77,
  longitude: -122.41 
};

const options = [
  {
    latitude: 37.77, 
    longitude: -122.43 
  },
  {
    latitude: 37.79,
    longitude: -122.40
  }
];

const shortest = shortestDistance(startingPoint, options);

console.log(shortest.index); // Index of closest option
console.log(shortest.distance); // Distance to closest option in miles

I recently started a new project that provides an alternative to paid distance matrix APIs. As a developer, I understand the value of open-source projects and the benefits they bring to the community. That's why I'm inviting fellow developers and hackers to contribute their ideas and expertise to this project.

You can find the project's code on my GitHub repository. Feel free to inspect the code, contribute new ideas, or suggest improvements to the existing codebase. Together, we can create a robust and cost-effective solution for calculating the shortest distance between two points based on their latitude and longitude coordinates.

Did you find this article valuable?

Support Lexy Thinks by becoming a sponsor. Any amount is appreciated!

ย