You can calculate the rotation angle between two LatLng
points to rotate the Marker
using some mathematics. The below code is generated using an AI tool, and it works perfectly. Here, startPoint
is the user's current location, and endPoint
is the position where the user will move, and we have to show a direction arrow from start
to end
point.
double calculateBearing(LatLng startPoint, LatLng endPoint) {
final double startLat = toRadians(startPoint.latitude);
final double startLng = toRadians(startPoint.longitude);
final double endLat = toRadians(endPoint.latitude);
final double endLng = toRadians(endPoint.longitude);
final double deltaLng = endLng - startLng;
final double y = Math.sin(deltaLng) * Math.cos(endLat);
final double x = Math.cos(startLat) * Math.sin(endLat) -
Math.sin(startLat) * Math.cos(endLat) * Math.cos(deltaLng);
final double bearing = Math.atan2(y, x);
return (toDegrees(bearing) + 360) % 360;
}
double toRadians(double degrees) {
return degrees * (Math.pi / 180.0);
}
double toDegrees(double radians) {
return radians * (180.0 / Math.pi);
}
Then, you can use this to rotate the Marker
like this:
Marker(
markerId: MarkerId(currentPosition.toString()),
position: currentPosition,
icon: movementArrow, // Custom arrow Marker
// Rotate the arrow in direction of movement. Func is defined below
rotation: calculateBearing(previousPosition, currentPosition) - 90,
anchor: const Offset(0.5, 0.5),
);
Here is a demo image: