Created
February 9, 2021 00:26
-
-
Save CosmoAbdon/bb28f683e308a2c5883b556178f8e6f6 to your computer and use it in GitHub Desktop.
Getting distance between 2 points using haversine
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 location { | |
| latitude: number, | |
| longitude: number, | |
| } | |
| const getDistanceBetweenTwoPoints = (user: location, company: location): number => { | |
| const p = 0.017453292519943295; // PI/180 (Evitar re-cálculo) | |
| const cos = Math.cos; | |
| const deltaLatitude = ((company.latitude - user.latitude) * p); | |
| const deltaLongitude = ((company.longitude - user.longitude) * p); | |
| const sinDeltaLatitude = cos(deltaLatitude)/2; | |
| const sinDeltaLongitude = ((1 - cos(deltaLongitude))/2); | |
| const userRadianLatitude = cos(user.latitude * p); | |
| const companyRadianLatitude = cos(company.latitude * p); | |
| var a = 0.5 - sinDeltaLatitude + userRadianLatitude * companyRadianLatitude * sinDeltaLongitude; | |
| return 12742 * Math.asin(Math.sqrt(a)); // O mesmo de fazer ((2 * RaioDaTerra) * ArcoSeno(Raiz(A)) | |
| } | |
| // Implementação | |
| const user: location = { latitude: -3.7404223, longitude: -38.5621739 } | |
| const company: location = { latitude: -3.74037582700665, longitude: -38.55872191910098 } | |
| const distance = getDistanceBetweenTwoPoints(user, company); | |
| console.log(distance) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment