nearestPointOnSegment static method
Calculates the nearest point on a line segment a, b to a target point p.
(Snap-to-road logic)
Implementation
static LatLng nearestPointOnSegment(LatLng p, LatLng a, LatLng b) {
double px = p.longitude;
double py = p.latitude;
double ax = a.longitude;
double ay = a.latitude;
double bx = b.longitude;
double by = b.latitude;
double dx = bx - ax;
double dy = by - ay;
if (dx == 0.0 && dy == 0.0) return a;
double t = ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy);
double clampedT = math.max(0.0, math.min(1.0, t));
return LatLng(ay + clampedT * dy, ax + clampedT * dx);
}