0

I have a map that displays some markers based on a given location. The location is set using a ChangeNotifier in a separate widget. I have no problem updating the location for the markers however, I would also like to set a new center of the map when the markers are updated.

I know that I can use the GoogleMapController to move the map but I am not sure where I would wire that in so that the map center updates when the location is updated.

The widget follows below:

class HotspotsMap extends StatelessWidget {
  final Completer<GoogleMapController> _controller = Completer<GoogleMapController>();
  final LocationNotifier locationNotifier;

  HotspotsMap({Key? key, required this.locationNotifier}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<LocationNotifier, HotspotNotifier>(
      create: (BuildContext context) {
        return HotspotNotifier();
      },
      update: (_, location, hotspotNotifier) => hotspotNotifier!..updateList(location.get()),
      child: Scaffold(
        appBar: AppBar(
          title: Text("Nearby Hotspots"),
          actions: <Widget>[
            set_location_icon,
          ],
        ),
        body: Center(
          child: Consumer2<HotspotNotifier, LocationNotifier>(
            builder: (context, notifier, location, child) {
              var _list = notifier.list;
              var position = location.get();
              if (position == null) {
                return Text("I don't know where you are");
              }
              Set<Marker> markers = {};
              _list.forEach((spot) {
                var newMarker = Marker(position: LatLng(spot.latitude, spot.longitude), markerId: MarkerId(spot.locId));
                markers.add(newMarker);
              });
              return GoogleMap(
                mapType: MapType.normal,
                markers: markers,
                initialCameraPosition: CameraPosition(
                  target: position,
                  zoom: 9,
                ),
                onMapCreated: (GoogleMapController controller) {
                  _controller.complete(controller);
                },
              );
            },
          ),
        ),
      ),
    );
  }
}
My Car
  • 4,198
  • 5
  • 17
  • 50
Schleis
  • 41,516
  • 7
  • 68
  • 87

1 Answers1

1

Based on your question this should do the job

yourMapController.animateCamera( 
        CameraUpdate.newCameraPosition(
              CameraPosition(target: marker's coordinates, zoom: 17) 

        )
      );

Check this for detailed exp https://www.fluttercampus.com/guide/257/move-google-map-camera-postion-flutter/#move-the-map-camera-to-new-coordinates

takudzw_M
  • 186
  • 1
  • 5
  • This doesn't quite do it, as I need to wrap it in an async function and await the CameraController – Schleis Mar 05 '23 at 16:17