有什么方法可以像原生 android 一样在 google 地图上对标记进行动画处理吗???
我正在使用
google_maps_flutter
。它为我们提供了一组要设置的标记。但是当我更改标记的坐标时,它只是消失并出现在新位置。
解决方案! https://pub.dev/packages/flutter_animarker 其作品!您只需要安装一个插件即可。
创建一个动画控制器,在两个点之间进行补间,并直接更新地图。使用动画值来更新标记的位置。使用曲线或持续时间参数更改动画的速度。
Tween 代码取自此处:https://gist.github.com/avioli/a0b800d6a5ed053871ab4eec8f57c2da
newLocation 是一个 latlng 值,传入目标 x、y 值。
class MapSample extends StatefulWidget {
final LatLng newLocation;
const MapSample({super.key, required this.newLocation});
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample>
with SingleTickerProviderStateMixin {
final Completer<GoogleMapController> _controller =
Completer<GoogleMapController>();
Map<String, Marker> markers = {};
late AnimationController _animationController;
late CurvedAnimation curvedAnimation;
LatLng oldLocation = const LatLng(x, y);
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
);
curvedAnimation =
CurvedAnimation(parent: _animationController, curve: Curves.ease);
_animationController.addListener(() {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
if (oldLocation == widget.newLocation) {
_animationController.reset();
}
Tween<LatLng> tween =
LatLngTween(begin: oldLocation, end: widget.newLocation);
Animation<LatLng> animation = tween.animate(curvedAnimation);
_animationController.forward().then((value) async {
oldLocation = widget.newLocation;
});
//print("${animation.value.latitude}, ${animation.value.longitude}");
markers["location"] = Marker(
markerId: const MarkerId("location"),
position: LatLng(animation.value.latitude, animation.value.longitude));
return GoogleMap(
mapType: MapType.normal,
markers: markers.values.toSet(),
initialCameraPosition: CameraPosition(
target: LatLng(x, y),
zoom: 21,
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
);
}
}
class LatLngTween extends Tween<LatLng> {
/// Creates a [LatLng] tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as an empty LatLng.
LatLngTween({required LatLng begin, required LatLng end})
: super(begin: begin, end: end);
/// Returns the value this variable has at the given animation clock value.
@override
LatLng lerp(double t) {
double lat, lng;
if (begin == null) {
lat = end!.latitude * t;
lng = end!.longitude * t;
} else if (end == null) {
lat = begin!.latitude * (1.0 - t);
lng = begin!.longitude * (1.0 - t);
} else {
print("${begin!.latitude}, ${end!.latitude}, $t");
lat = lerpDouble(begin!.latitude, end!.latitude, t);
lng = lerpDouble(begin!.longitude, end!.longitude, t);
}
return LatLng(lat, lng);
}
@protected
double lerpDouble(double a, double b, double t) {
return a + (b - a) * t;
}
}