Search code examples
flutterdartgoogle-maps-flutter

Update Google Map center after ChangeNotifier update


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);
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

Solution

  • 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