What is the best way to calculate the distance between two nodes? For instance I have the Longitude and Latitude of both points, but want to calculate the distance between these two points.
It depends, do you want:
- The line of sight distance.
- The travel distance.
Line of sight distance
If you'd like the straight line distance, then you could use the haversine formula. Here is a JavaScript example from here:
function haversineDistance(coords1, coords2, isMiles) {
function toRad(x) {
return x * Math.PI / 180;
}
var lon1 = coords1[0];
var lat1 = coords1[1];
var lon2 = coords2[0];
var lat2 = coords2[1];
var R = 6371; // km
var x1 = lat2 - lat1;
var dLat = toRad(x1);
var x2 = lon2 - lon1;
var dLon = toRad(x2)
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
if(isMiles) d /= 1.60934;
return d;
}
Travel distance
If you would like the travel distance, then you could use the Google Maps API. The easiest is to use the @google/maps npm module. Here is an example:
const google_maps = require("@google/maps");
const googleMapsClient = google_maps.createClient({
key: "your-key",
Promise: Promise
});
const origin = "-33.888187, 18.634691";
const destination = "-34.425036, 21.282965";
export async function run() {
let mapClient = await googleMapsClient
.distanceMatrix({
origins: [origin],
destinations: [destination],
mode: "driving",
units: "metric"
})
.asPromise()
.then(response => {
if (response && response.status === 200) {
const data = response.json.rows[0].elements[0];
console.log(`data received: ${JSON.stringify(data, null, 2)}`);
const distance = data.distance.text;
const duration = data.duration.text;
const duration_in_seconds = data.duration.value;
console.log(
`Distance ${distance} Duration ${duration} (${duration_in_seconds}seconds)`
);
return {
distance: distance,
duration: duration,
duration_in_seconds: duration_in_seconds
};
} else {
console.log(`No data, status ${JSON.stringify(response)}`);
}
})
.catch(err => {
console.log(err);
});
}
1 Like
Be mindful that the Google Maps API is subject to Terms & Conditions. An alternative is Mapbox that provides similar functionality with more lenient terms.
Thank you Captain Responsible