使用 Flutter 在 Google 地图标记周围居中摄像头位置

May*_*lor 6 google-maps dart flutter

我正在使用google_maps_flutter: ^0.5.13开发一个基本的“谷歌地图上的多个标记”类型的 Flutter 屏幕。

我很好奇其他人是如何initialCameraPostionGoogleMap()班级设置的。我要么

  1. 最初将其设置为静态
  2. 在该getMapMarkers()函数中,我将调用 a setMarkers(List<dynamic> markers)(接收标记或对象列表)并GeoPoint从标记列表中获取其中之一并使用它来设置initialCameraPosition.

     class MapScreenState extends State<MapScreen> {
    
      GoogleMapController _mapController;
    
      // Method #1
      static CameraPosition _initialCameraPosition =
          CameraPosition(target: const LatLng(26.357540, -81.785290), zoom: 12);
    
      void _onMapCreated(GoogleMapController controller) {
        _mapController = controller;
        _getMapMarkers();
      }
    
      @override
      Widget build(BuildContext context) {
        return Stack(children: <Widget>[_googleMap(context)]);
      }
    
      Widget _googleMap(BuildContext context) {
        return Column(children: <Widget>[
          Expanded(
            child: Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: GoogleMap(
                initialCameraPosition: _initialCameraPosition,
                onMapCreated: _onMapCreated,
                mapType: MapType.normal,
                markers: Set<Marker>.of(markers.values),
              ),
            ),
          )
        ]);
      }
    }
    
    // Method #2
    void _setCenter(List<dynamic> markers) {
      GeoPoint geo = markers[0].geocode;
      setState(() {
        _initialCameraPosition =
            CameraPosition(target: LatLng(geo.latitude, geo.longitude), zoom: 12);
      });
    }
    
    Run Code Online (Sandbox Code Playgroud)

Leo*_*nth 6

initialCameraPosition仅适用于初始时间。您可以使用以下方式移动相机。我们已经有了一个使用onMapCreatedhook的相机控制器。

  void _onMapCreated(GoogleMapController controller) {
    _mapController = controller;
    _getMapMarkers();
  }
Run Code Online (Sandbox Code Playgroud)

使用此_mapController我们可以访问moveCamera功能并将相机移动到标记位置。

_mapController.moveCamera(CameraUpdate.newLatLng(<LatLng one of your marker position>));
Run Code Online (Sandbox Code Playgroud)

例子:

_mapController.moveCamera(CameraUpdate.newLatLng(LatLng(markerLat,markerLng)));
Run Code Online (Sandbox Code Playgroud)