Skip to content

Bug: nearestPointOnSegment returns incorrect endpoint when in opposite hemispheres #2934

@bratter

Description

@bratter

Hi and thank you to all the contributors for a wonderful package.

Summary

I've found a bug in @turf/nearest-point-on-line, specifically in nearestPointOnSegment.

In general, nearestPointOnSegment potentially returns the wrong point when the line segment is at least partially in the other hemisphere to the target point.

Version

This was noticed in v7.2.0, and is still present in the current master branch.

Reproduction Example

A simple reproduction of an instance of this is:

const p = turf.point([-45, -88]);
const l = turf.lineString([[25, 88], [25, -70]]);

const result = turf.nearestPointOnLine(l, p);

The result is then:

{
    "type": "Feature",
    "properties": {
        "dist": 19650.79608235262,
        "multiFeatureIndex": 0,
        "location": 6.32076866494081e-12,
        "index": 0
    },
    "geometry": {
        "type": "Point",
        "coordinates": [
            25.000000000000007,
            88.00000000000006
        ]
    }
}

Expected Behavior

In this specific instance, the returned point should be the other end of the segment, i.e., [25, -70], the distance reduced accordingly as it would use the other point (~2158km).

Root Cause

Issue is due to the angular check for the closest intersection of the projected great circle - I believe the methodology fails when the true closest point is >Pi radians in angular separation from the test point.

Fix

The fix seems to be to do a dot product comparison rather than the current angular comparison here.

If a maintainer is good with this, I can do a PR with the code + plus an extra test.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions