0

I have an array of geocoordinates as follows:

const coordinates = [
    { lat: 40.54735374702427, lon: -74.39442702644757 },
    { lat: 40.27735374702427, lon: -74.43442702644757 },
    { lat: 40.19735374202427, lon: -74.84442702644757 }
]

How do I get the total distance with all the coordinates combined like so: Distance between coords[0] - coords[1] added to coords[1] - coords[2] etc. for all the elements in the array to get the total distance in miles. I also want to take into account the curvature of the earth.

NOTE: All coordinates are made up for the purpose of this question.

ranep12
  • 21
  • 4
  • Do you want to take into account the curvature of the earth or just the straight line distance? – 001 Apr 19 '21 at 13:43

1 Answers1

-1

index.js

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

function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
    var earthRadiusKm = 6371;

    var dLat = degreesToRadians(lat2 - lat1);
    var dLon = degreesToRadians(lon2 - lon1);

    lat1 = degreesToRadians(lat1);
    lat2 = degreesToRadians(lat2);

    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return earthRadiusKm * c;
}



const coordinates = [
    { lat: 40.54735374702427, lon: -74.39442702644757 },
    { lat: 40.27735374702427, lon: -74.43442702644757 },
    { lat: 40.19735374202427, lon: -74.84442702644757 }
];

let totalDistanceInKm = 0;

for (let i = 0; i < coordinates.length - 1; i++) {
    totalDistanceInKm += distanceInKmBetweenEarthCoordinates(coordinates[i].lat, coordinates[i].lon, coordinates[i + 1].lat, coordinates[i + 1].lon);
}

let distanceInMiles = totalDistanceInKm * 0.621371;

console.log(distanceInMiles);
Suresh Mangs
  • 705
  • 8
  • 19