How to setCenter() leaflet map in flutter

不问归期 提交于 2020-07-22 05:36:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/58746679/how-to-setcenter-leaflet-map-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!