Skip to content

Commit

Permalink
Merge branch 'master' of github.com:manuelbieh/geolib
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelbieh committed Jun 23, 2019
2 parents 0a55d4b + 46590b0 commit 6c72bd0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
22 changes: 6 additions & 16 deletions src/getDistance.test.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import getDistance from './getDistance';

// Icecream for the first person who can tell me why this is NaN:
// console.log(
// 'distance:',
// getDistance(
// { latitude: 51.516241842, longitude: 7.456494328 },
// { latitude: 51.516241842, longitude: 7.456494328 }
// )
// );

describe('getDistance', () => {
it('should calculate the distance between any two points', () => {
expect(
Expand Down Expand Up @@ -46,12 +37,11 @@ describe('getDistance', () => {
)
).toBe(0);

// TODO: WTF! Why is this NaN?!
// expect(
// getDistance(
// { latitude: 51.516241842, longitude: 7.456494328 },
// { latitude: 51.516241842, longitude: 7.456494328 }
// )
// ).toBe(0);
expect(
getDistance(
{ latitude: 51.516241842, longitude: 7.456494328 },
{ latitude: 51.516241842, longitude: 7.456494328 }
)
).toBe(0);
});
});
16 changes: 12 additions & 4 deletions src/getDistance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import toRad from './toRad';
import { earthRadius } from './constants';
import { GeolibInputCoordinates } from './types';

const normalizeACosArg = (val: number): number => {
if (val > 1) return 1;
if (val < -1) return -1;
return val;
};

// Calculates the distance between two points.
// This method is simple but also more inaccurate
const getDistance = (
Expand All @@ -21,10 +27,12 @@ const getDistance = (

const distance =
Math.acos(
Math.sin(toRad(toLat)) * Math.sin(toRad(fromLat)) +
Math.cos(toRad(toLat)) *
Math.cos(toRad(fromLat)) *
Math.cos(toRad(fromLon) - toRad(toLon))
normalizeACosArg(
Math.sin(toRad(toLat)) * Math.sin(toRad(fromLat)) +
Math.cos(toRad(toLat)) *
Math.cos(toRad(fromLat)) *
Math.cos(toRad(fromLon) - toRad(toLon))
)
) * earthRadius;

return Math.round(distance / accuracy) * accuracy;
Expand Down

0 comments on commit 6c72bd0

Please sign in to comment.