Last active
February 17, 2020 21:12
-
-
Save gabrielsaints/183277933027a4368ef1523e8ea6b15c 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
interface GeoLocalizer { | |
latitude: number; | |
longitude: number; | |
} | |
interface DistanceCalculator { | |
from: GeoLocalizer; | |
to: GeoLocalizer; | |
} | |
export function calculateDistance({ | |
from: { latitude: latitudeFrom, longitude: longitudeFrom }, | |
to: { latitude: latitudeTo, longitude: longitudeTo } | |
}: DistanceCalculator): number { | |
const toRad = (value: number): number => { | |
return (value * Math.PI) / 180; | |
}; | |
const radius = 6371; // km | |
const dLat = toRad(latitudeTo - latitudeFrom); | |
const dLon = toRad(longitudeTo - longitudeFrom); | |
const latitudeFromRad = toRad(latitudeFrom); | |
const latitudeToRad = toRad(latitudeTo); | |
const a = | |
Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.sin(dLon / 2) * | |
Math.sin(dLon / 2) * | |
Math.cos(latitudeFromRad) * | |
Math.cos(latitudeToRad); | |
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
return radius * c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment