diff --git a/package.json b/package.json index 3fac99b..4068379 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,6 @@ "test": "jest", "typecheck": "tsc --noEmit" }, - "dependencies": {}, "devDependencies": { "@babel/cli": "^7.8.4", "@babel/core": "^7.9.6", diff --git a/src/getDistanceFromLine.test.js b/src/getDistanceFromLine.test.js index 82e12ea..f7c52a1 100644 --- a/src/getDistanceFromLine.test.js +++ b/src/getDistanceFromLine.test.js @@ -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(); }); }); diff --git a/src/getDistanceFromLine.ts b/src/getDistanceFromLine.ts index 6634f7b..f4db1b5 100644 --- a/src/getDistanceFromLine.ts +++ b/src/getDistanceFromLine.ts @@ -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) {