Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points.

 const latsLngs = [
  {
    lat: 40.78340415946297,
    lng: -73.9714273888736,
  },
  {
    lat: 40.778399767985704,
    lng: -73.97915215083648,
  },
  {
    lat: 40.7722899997727,
    lng: -73.96842331477691,
  },
  {
    lat: 40.76617966968189,
    lng: -73.97769302913238,
  },
  {
    lat: 40.76838985393672,
    lng: -73.96147102901031,
  },
  {
    lat: 40.781909380720485,
    lng: -73.96636337825348,
  },
];

Answer №1

If you're looking to calculate distance, I recommend utilizing the geolib.getDistance function, which will provide the distance in meters.

You can easily convert meters to miles and feet by considering that there are 0.3048 meters in a foot and 5280 feet in a mile.

const latsLngs = [ { lat: 40.78340415946297, lng: -73.9714273888736, }, { lat: 40.778399767985704, lng: -73.97915215083648, }, { lat: 40.7722899997727, lng: -73.96842331477691, }, { lat: 40.76617966968189, lng: -73.97769302913238, }, { lat: 40.76838985393672, lng: -73.96147102901031, }, { lat: 40.781909380720485, lng: -73.96636337825348, }, ]; 

function getDistanceInMilesAndFeet(a, b) {
    const distanceMeters = geolib.getDistance(a, b, 0.01);
    return metersToMilesAndFeet(distanceMeters);
}

function metersToMilesAndFeet(meters) {
    const totalFeet = meters / 0.3048;
    const miles = Math.floor(totalFeet / 5280);
    const feet = Math.round(totalFeet % 5280);
   return `${miles} miles, ${feet} feet`;
}

// Show distance from point 1 to the other points...
const a = latsLngs[0]; 
latsLngs.forEach((b, idx) => { 
    if (idx > 0) console.log(`Distance from point 1 to point ${idx + 1}:`, getDistanceInMilesAndFeet(a, b));
})
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddbab8b2b1b4bf9deef3eef3ec">[email protected]</a>/lib/index.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to link a particular model table with a designated user table?

Hey everyone, I'm new to stack overflow and this is my first question. I hope it's clear enough for you all to understand. I'm currently working on a budget API using Node.js, Sequelize, Express, and PostgreSQL. The API allows users to add/ ...

Comparing strings with data in objects using Angular

all. I have a query. What is the optimal method for comparing data? For instance, if you have a constant response = 225235743; And I aim to locate and exhibit all data in an object with the same ID as the one in this response. This needs to be resolved ...

What are the most optimal configurations for tsconfig.json in conjunction with node.js modules?

Presently, I have 2 files located in "./src": index.ts and setConfig.ts. Both of these files import 'fs' and 'path' as follows: const fs = require('fs'); const path = require('path'); ...and this is causing TypeScr ...

`Typescript does not adhere to the specified type when used inside a for loop with a local

This code snippet declares a variable venuelist of type Venue array and initializes it as an empty array. The type Venue has a property named neighborhood. There is a for loop that iterates through the venuelist array and checks if the neighborhoods matc ...

Altering the properties of every item within a v-for loop's array

I'm currently exploring Vue's approach to writing JavaScript. Let's consider this situation: In the .vue template <button v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button> < ...

Is there a way to enable live-reload for a local npm package within a monorepo setup?

Currently, I am in the process of setting up a monorepo workspace that will house a Vue 3 application (using vite and TypeScript), cloud functions, and a shared library containing functions and TypeScript interfaces. I have successfully imported my local ...

Leverage the useParams data to serve as a state object key in the useSelector function using TypeScript

Looking to access state data using a key obtained from useParams? Here's an example: export const MainPageSection = (props:MainPageSectionPropsType) => { const params = useParams(); const currentSection = params.section const excursions ...

Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked. However, we are facing issues where clicking on the order button doesn't register in the applicat ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

Guide to adding sound effects to your Vue 3 app using the Composition API

I'm having trouble setting up a basic button click feature in Vue 3 Composition API to play a sound effect. In my setup function, I have imported an mp3 sound effect from the assets folder and passed it into a ref method with an HTMLAudioElement type, ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Check if the element is located on the active tab using jQuery

I have implemented a tab system to organize a lengthy form with multiple input fields. The form consists of 4 tabs, and beneath them, there is a preview section displaying the user's selections. In this preview area, I added icons that enable users ...

What exactly is a NativeScript app: is it the experience users have on their mobile devices, or the product they download from the app store?

Currently, I am diving into the world of Angular and exploring how to develop Angular applications with TypeScript while working on a C# ASP.Net Core Web Api project as the server side component. My question is this - if I create a NativeScript app in add ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...

"I'm experiencing an issue in Laravel where the Ion range slider's color and dragger are

I'm currently implementing ion-rangeslider into my project. Here is the HTML code I've used: <div style="position: relative; padding: 200px;"> <div> <input type="text" id="range" value="" name= ...

NextJs redirection techniquesWould you like to learn the best ways

Currently, I am developing an application using NextJS with Firebase authentication integration. Upon successful authentication, my goal is to retrieve additional customer details stored in a MongoDB database or create a new document for the customer upon ...

Issue with regex replacement behaving differently in Node compared to console

I am having trouble properly escaping commas in a sentence. Oddly enough, my replace method is not functioning correctly in node, while it works fine in the Chrome console. Is there anyone who has a solution to this issue? It seems to be occurring with al ...