Adi Firman Ilham
Adi Firman Ilham

Reputation: 144

How to setCenter() leaflet map in flutter

I'm working on leaflet map in flutter. I built marker generator in order to make them move dynamically. I have a button to make the map center on my determined coordinate.

This is the widget to create map.

Widget _initMap(BuildContext context){
  return Stack(
    children: <Widget>[
      new FlutterMap(
          options: MapOptions(
            minZoom: _minzoom,
            maxZoom: _maxzoom,
            center: LatLng(mylatitude,mylongitude),
          ),
          layers: [
            new TileLayerOptions(
                urlTemplate:
                'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                subdomains: ['a', 'b', 'c']),
            new MarkerLayerOptions(
                markers: _generateMarker(context)
            ),
          ]
         ),
      Align(
        alignment: Alignment.bottomRight,
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: new FloatingActionButton(
            onPressed: (){_initMap(context);},
            child: Icon(Icons.gps_fixed),
          ),
        ),
      ),
    ],
  );
}

I expect the button to recreate the widget _initMap so that the map will reset its center according to variable mylatitude and mylongitude, because those two variables change dynamically. Anyone know how to do this?

Upvotes: 1

Views: 2730

Answers (1)

user10552463
user10552463

Reputation: 11

You have to pass a MapController to your Flutter FlutterMap widget and in your onPressed trigger the .move() method of the controller.

The following code lets you move from the initial center to the eiffel tower, when you click the FAB. Just init your map on app start or whenever you want to.

MapController _mapController = MapController();

Widget _initMap(BuildContext context){
  return Stack(
    children: <Widget>[
      new FlutterMap(
          mapController: _mapController,
          options: MapOptions(
            minZoom: _minzoom,
            maxZoom: _maxzoom,
            center: LatLng(mylatitude,mylongitude),
          ),
          layers: [
            new TileLayerOptions(
                urlTemplate:
                'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                subdomains: ['a', 'b', 'c']),
            new MarkerLayerOptions(
                markers: _generateMarker(context)
            ),
          ]
         ),
      Align(
        alignment: Alignment.bottomRight,
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: new FloatingActionButton(
            onPressed: (){
              _mapController.move(LatLng(48.8587372,2.2945457), 13);
            },
            child: Icon(Icons.gps_fixed),
          ),
        ),
      ),
    ],
  );
}

Upvotes: 1

Related Questions