Function tryNearestPointOnSegment

Find the point on a finite route segment closest to a position.

bool tryNearestPointOnSegment(T)(
  const Geodesic!T solver,
  const GeographicCoordinate!T start,
  const GeographicCoordinate!T end,
  const GeographicCoordinate!T target,
  out GeodesicSegmentNearestResult!T result
) pure nothrow @nogc @safe
if (isGeodesyScalar!T);

Supply the route's start A, end B, and the position to check. The result gives the nearest point on the segment and its distance from the position. If the nearest point on the extended route lies beyond A or B, the nearest segment point is the corresponding endpoint.

The result also describes the extended route: alongTrack measures from A in the A-to-B direction; signedCrossTrack is positive on the right and negative on the left. These values describe the extended route, not necessarily the distance to the finite segment.

A coincident A/B pair is rejected because its orientation, along-track direction, and cross-track sign are undefined.

Very distant configurations for which the local gnomonic construction is over its horizon or fails to converge return false.

Parameters

NameDescription
solver Valid prepared geodesic solver.
start Segment start A.
end Segment end B.
target Geographic point whose nearest segment point is requested.
result Receives bounded nearest-point and supporting-line quantities.

Returns

true on a finite converged solution; otherwise false. Failure resets result to .init.

Example

Example finding an interior nearest point without throwing.

const solver =
    Geodesic!double.fromEllipsoid(
        Ellipsoid!double.fromInverseFlattening(
            6_378_137.0,
            298.257223563));

const a =
    GeographicCoordinate!double.fromComponents(
        Latitude!double.fromDegrees(0.0),
        Longitude!double.fromDegrees(-20.0));

const b =
    GeographicCoordinate!double.fromComponents(
        Latitude!double.fromDegrees(0.0),
        Longitude!double.fromDegrees(20.0));

const target =
    GeographicCoordinate!double.fromComponents(
        Latitude!double.fromDegrees(-2.0),
        Longitude!double.fromDegrees(3.0));

GeodesicSegmentNearestResult!double result;

assert(tryNearestPointOnSegment(
    solver,
    a,
    b,
    target,
    result));

assert(result.isValid);
assert(result.kind == GeodesicSegmentNearestKind.interior);
assert(result.signedCrossTrack > 0.0);