getClosestPointOnPathAsDistanceOnPath function

double getClosestPointOnPathAsDistanceOnPath(
  1. Path path,
  2. Offset queryPoint
)

Implementation

double getClosestPointOnPathAsDistanceOnPath(Path path, Offset queryPoint) {
  PathMetric metrics = path.computeMetrics().toList()[0];

  int nSteps = 100;
  double pathLength = metrics.length;
  double stepSize = pathLength / nSteps;

  List<Offset> pointsOnPath = [];

  double minDistance = double.infinity;

  // x, y, and length on the path where that point lies
  double closestPoint = -1;

  // Sample nSteps points on the path
  for (var step = 0.0; step < pathLength; step += stepSize) {
    final tangent = metrics.getTangentForOffset(step)!;
    pointsOnPath.add(tangent.position);
  }

  // Find the point on the path closest to the query
  for (var iPoint = 0; iPoint < pointsOnPath.length; iPoint++) {
    final point = pointsOnPath[iPoint];
    final distance = distance2D(point, queryPoint);
    if (distance < minDistance) {
      minDistance = distance;
      closestPoint = iPoint * stepSize;
    }
  }

  return closestPoint;
}