Update distanceBetweenCoordinates

This commit is contained in:
Linus Groh
2019-10-02 19:23:45 +01:00
parent 12910fe66d
commit da7a0aa5d6
2 changed files with 24 additions and 18 deletions

View File

@@ -35,27 +35,33 @@ export const isIsoDate = s => ISO_DATE_REGEXP.test(s);
export const degreesToRadians = degrees => (degrees * Math.PI) / 180;
/**
* Calculate the distance between two coordinates.
* https://stackoverflow.com/a/365853/5952681
* Calculate the distance between two coordinates. Uses the haversine formula,
* which is not 100% accurate - but that's not the goal here.
*
* https://en.wikipedia.org/wiki/Haversine_formula
*
* @param {Coordinate} c1 First coordinate
* @param {Coordinate} c2 Second coordinate
* @return {Number} Distance in meters
*/
export const distanceBetweenCoordinates = (c1, c2) => {
const latDistanceInRad = degreesToRadians(c1.lat - c2.lat);
const lngDistanceInRad = degreesToRadians(c1.lng - c2.lng);
const lat1InRad = degreesToRadians(c1.lat);
const lat2InRad = degreesToRadians(c2.lat);
const a =
Math.sin(latDistanceInRad / 2) * Math.sin(latDistanceInRad / 2) +
Math.sin(lngDistanceInRad / 2) *
Math.sin(lngDistanceInRad / 2) *
Math.cos(lat1InRad) *
Math.cos(lat2InRad);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Return distance in meters
return EARTH_RADIUS_IN_KM * c * 1000;
const r = EARTH_RADIUS_IN_KM * 1000;
const phi1 = degreesToRadians(c1.lat);
const phi2 = degreesToRadians(c2.lat);
const lambda1 = degreesToRadians(c1.lng);
const lambda2 = degreesToRadians(c2.lng);
const d =
2 *
r *
Math.asin(
Math.sqrt(
Math.sin((phi2 - phi1) / 2) ** 2 +
Math.cos(phi1) *
Math.cos(phi2) *
Math.sin((lambda2 - lambda1) / 2) ** 2
)
);
return d;
};
/**