Skip to content

Commit

Permalink
Fix: getDistanceFormLine returning NaN when point on line or line is …
Browse files Browse the repository at this point in the history
…a point

Co-authored-by: Cédric <[email protected]>
  • Loading branch information
timvahlbrock committed Dec 10, 2023
1 parent 26ec179 commit e1817d9
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 21 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
"test": "jest",
"typecheck": "tsc --noEmit"
},
"dependencies": {},
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.9.6",
Expand Down
59 changes: 39 additions & 20 deletions src/getDistanceFromLine.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,26 +120,45 @@ describe('getDistanceFromLine', () => {
0.1
)
).not.toBeNaN();
});

// TODO: If the point is directly on the line(?) it returns NaN
// Verify and fix
// https://github.com/manuelbieh/geolib/issues/129
// expect(
// getDistanceFromLine(
// {
// latitude: 53,
// longitude: 5,
// },
// {
// latitude: 53,
// longitude: 5,
// },
// {
// latitude: 54,
// longitude: 6,
// },
// 1
// )
// ).not.toBeNaN();
it('should not return NaN if point is on line', () => {
expect(
getDistanceFromLine(
{
latitude: 53,
longitude: 5,
},
{
latitude: 53,
longitude: 5,
},
{
latitude: 54,
longitude: 6,
},
1
)
).not.toBeNaN();
});

it('should not return NaN if lineStart and lineEnd are (effectively) the same', () => {
expect(
getDistanceFromLine(
{
latitude: 51.5588,
longitude: 7.06044,
},
{
latitude: 51.42829895019531,
longitude: 7.05250883102417,
},
{
latitude: 51.42829895019531,
longitude: 7.0525078773498535,
},
1
)
).not.toBeNaN();
});
});
11 changes: 11 additions & 0 deletions src/getDistanceFromLine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ const getDistanceFromLine = (
robustAcos((d2 * d2 + d3 * d3 - d1 * d1) / (2 * d2 * d3))
);

const pointAtLineStart = d1 === 0;
const pointAtLineEnd = d2 === 0;
if (pointAtLineStart || pointAtLineEnd) {
return 0;
}

const lineLengthZero = d3 === 0;
if (lineLengthZero) {
return d1;
}

// if the angle is greater than 90 degrees, then the minimum distance is the
// line from the start to the point
if (alpha > Math.PI / 2) {
Expand Down

0 comments on commit e1817d9

Please sign in to comment.