My goal is to draw a polyline from a given LatLng
coordinate to the center of the screen. I’ve marked the center of the screen with an icon.
When onCameraIdle
is triggered, a method is run to determine between which coordinates the polyline should be drawn.
However, sometimes the last calculated and updated polyline is not rendered. This happens seldom on an emulator, although it does happen and I’ve recorded it. But it happens very frequently on a real device. When a rebuild is triggered, e.g. by zooming, or starting a camera movement, or expanding a drawer on the device, the latest polyline is drawn.
You can see on the gif below, on the third camera movement that the polyline is not rendered to match the center of the screen. But when I slightly pan the camera which triggers a rebuild, the last calculated polyline is rendered correctly.
Any idea why this is happening?
Minimal reproducible example widget as below:
class MapDemo extends StatefulWidget {
const MapDemo({
super.key,
});
@override
State<MapDemo> createState() => _MapDemoState();
}
class _MapDemoState extends State<MapDemo> {
final currentLocation = const LatLng(57.02083060347767, 16.864670327078553);
Set<Polyline> polylines = {};
late GoogleMapController mapController;
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: [
GoogleMap(
onCameraMoveStarted: () {},
onCameraIdle: () async {
await drawPolyline();
},
onMapCreated: (GoogleMapController controller) {
setState(() {
mapController = controller;
});
},
initialCameraPosition: CameraPosition(
target: currentLocation,
zoom: 17,
),
polylines: polylines,
),
const Icon(Icons.adjust, color: Colors.black),
],
);
}
Future<void> drawPolyline() async {
final bounds = await mapController.getVisibleRegion();
final screenCenter = LatLng(
(bounds.northeast.latitude + bounds.southwest.latitude) / 2,
(bounds.northeast.longitude + bounds.southwest.longitude) / 2,
);
setState(() {
polylines = {
Polyline(
polylineId: const PolylineId('measurement'),
points: [currentLocation, screenCenter],
width: 3,
),
};
});
}
}