Created
October 12, 2018 01:00
-
-
Save TylerK/be1ac991fbd86cd8324f3c9180f661f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type GpsCoordinate = number; | |
type DistanceMeasure = number; | |
type DistanceValue = number; | |
type Degrees = number; | |
type Radians = number; | |
interface GpsCoordinates { | |
lat1: GpsCoordinate; | |
long1: GpsCoordinate; | |
lat2: GpsCoordinate; | |
long2: GpsCoordinate; | |
} | |
function convertKmToMiles(km: DistanceMeasure): DistanceMeasure { | |
return km * 0.621371; | |
} | |
function distanceInKm(distance: DistanceValue): DistanceValue { | |
const EARTH_RADIUS_KM = 6371; | |
return distance * EARTH_RADIUS_KM; | |
} | |
function degreesToRadians(degrees: Degrees): Radians { | |
return degrees * (Math.PI / 180); | |
} | |
export default function distanceBetweenPointsInMiles(coordinates: GpsCoordinates): DistanceValue { | |
const { lat1, long1, lat2, long2 } = coordinates; | |
const lat: Radians = degreesToRadians(lat2 - lat1); | |
const long: Radians = degreesToRadians(long2 - long1); | |
/** | |
* This uses the ‘haversine’ formula to calculate the great-circle distance between two points. | |
* Read more: https://www.movable-type.co.uk/scripts/latlong.html | |
*/ | |
const a: number = | |
Math.sin(lat / 2) * Math.sin(lat / 2) + | |
Math.cos(degreesToRadians(lat1)) * Math.cos(degreesToRadians(lat2)) * | |
Math.sin(long / 2) * Math.sin(long / 2); | |
const c: number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
const d: number = distanceInKm(c); | |
return convertKmToMiles(d); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment