I have a array of latitudes and longitudes and I need to calculate the distance in miles and feet between the coordinates (In JavaScript or Typescript).
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,
},
];
I'd suggest using geolib.getDistance, this will return distance in meters.
We can easily convert meters to miles and feet, knowing that there are 0.3048 meters in one 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/geolib@3.3.1/lib/index.js"></script>