Skip to content

Instantly share code, notes, and snippets.

@nakul5harma
Last active March 20, 2022 10:06
Show Gist options
  • Save nakul5harma/3f459045a45be0921f9abef3207adeb2 to your computer and use it in GitHub Desktop.
Save nakul5harma/3f459045a45be0921f9abef3207adeb2 to your computer and use it in GitHub Desktop.
Radial distance between two locations using haversine formula
export interface Coordinates {
latitude: number;
longitude: number;
}
const getRadiansFromDegrees = (degrees: number) => {
return (degrees * Math.PI) / 180;
};
export const calculateRadialDistanceBetweenCoordinates = (
sourceCoordinates: Coordinates,
destinationCoordinates: Coordinates
) => {
const EARTH_RADIUS_IN_METERS = 6371e3;
const sourceLatitudeInRadians = getRadiansFromDegrees(
sourceCoordinates.latitude
);
const destinationLatitudeInRadians = getRadiansFromDegrees(
destinationCoordinates.latitude
);
const latitudeDifference = getRadiansFromDegrees(
destinationCoordinates.latitude - sourceCoordinates.latitude
);
const longitudeDifference = getRadiansFromDegrees(
destinationCoordinates.longitude - sourceCoordinates.longitude
);
const haversineOfCentralAngle =
Math.pow(Math.sin(latitudeDifference / 2), 2) +
Math.cos(sourceLatitudeInRadians) *
Math.cos(destinationLatitudeInRadians) *
Math.pow(Math.sin(longitudeDifference / 2), 2);
const centralAngle =
2 *
Math.atan2(
Math.sqrt(haversineOfCentralAngle),
Math.sqrt(1 - haversineOfCentralAngle)
);
const distanceInMeters = EARTH_RADIUS_IN_METERS * centralAngle;
return Number(distanceInMeters.toFixed(3));
};
export const isDeliveryPartnerInAllowedRange = (
sourceCoordinates: Coordinates,
destinationCoordinates: Coordinates,
allowedMaxDistanceInMeters: number
) => {
const radialDistanceInMeters = calculateRadialDistanceBetweenCoordinates(
sourceCoordinates,
destinationCoordinates
);
if (radialDistanceInMeters > allowedMaxDistanceInMeters) {
return false;
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment