projectPointOntoGeodesicLine static method
Projects a given point onto a geodesic line defined by two endpoints.
point - The LatLng coordinates of the point to project.
start - The LatLng coordinates of the starting point of the geodesic line.
end - The LatLng coordinates of the ending point of the geodesic line.
Returns the projected point as a LatLng object.
Implementation
static LatLng projectPointOntoGeodesicLine(
LatLng point, LatLng start, LatLng end) {
const double earthRadius = 6371000; // Earth's radius in meters
final Distance distance = const Distance();
// Calculate the initial bearing from start to end
final double initialBearingValue = initialBearing(start, end);
// Calculate the distance between start and the given point
final double distanceToStart = distance(start, point);
// Calculate the angular distance in radians
final double angularDistance = distanceToStart / earthRadius;
// Calculate the final bearing using the initial bearing and
// angular distance
final double finalBearing =
asin(sin(angularDistance) * sin(initialBearingValue));
// Calculate the destination point (projection) on the line
final double lat1 = (start.latitude).toRadians();
final double lon1 = (start.longitude).toRadians();
final double lat2 = asin(sin(lat1) * cos(angularDistance) +
cos(lat1) * sin(angularDistance) * cos(finalBearing));
final double lon2 = lon1 +
atan2(sin(finalBearing) * sin(angularDistance) * cos(lat1),
cos(angularDistance) - sin(lat1) * sin(lat2));
return LatLng((lat2).toDegrees(), (lon2).toDegrees());
}