Reputation: 627
Can anyone share a documentation / code sample for Flutter google maps plugin where I can rotate the marker ( ex: a car icon ) according to the driving direction. I saw this can be achieved on native library by rotating the marker. But couldn't fjnd any option to rotate the marker in Flutter.
I guess we need to consider below points while rotating the marker. Please add your thoughts on this as well.
Map North Direction. Devices rotation from compass.
Thanks
Upvotes: 15
Views: 12542
Reputation: 83
If you are using the geolocator plugin the position object has the heading property too
Marker(..., rotation: position.heading);
Upvotes: 1
Reputation: 134
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:
Upvotes: 1
Reputation: 419
https://pub.dev/packages/location plugin :
Marker( rotation: currentLocation.heading )
Upvotes: 16
Reputation: 19
you can add compass plugin https://pub.dev/packages/flutter_compass and simply set the result direction to marker
Upvotes: 1