【问题标题】:Flutter: How to animate the camera of Google MapsFlutter:如何为谷歌地图的相机设置动画
【发布时间】:2020-12-24 23:54:00
【问题描述】:

我正在尝试构建一个加载 GoogleMap() 的应用,然后在获取用户纬度和经度后移动到该特定位置。

我想出了这个想法(下面的代码),但它只有在我重新启动应用程序时才有效,如果我不这样做,它会给出错误:animateCamera 在 null 上被调用。

这怎么可能?我该如何解决?

感谢您的回答:D

...

var mapController;

...

GoogleMap createMap() {
    var initMap = GoogleMap(
      onMapCreated: onMapCreated,
      initialCameraPosition:
          CameraPosition(target: LatLng(47.290542, 8.322641), zoom: 6.7),
    );
    return initMap;
  }
  
  ...

  void onMapCreated(controller) {
    mapController = controller;
  }
 
 ...
 
   void moveCameraToUserLocation(searchedLocation2) async {
    var location = await Geocode().getLatLng(searchedLocation2);
    print("moving to: $location");
    mapController.animateCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
          target: location,
          zoom: 20,
        ),
      ),
    );
    
 ...
 
 build(context) {

    return Scaffold(

      body: createMap(),

...

【问题讨论】:

    标签: google-maps flutter google-maps-api-3


    【解决方案1】:

    您可能在创建地图之前调用 moveCameraToUserLocation 函数。当您调用 thi 函数时,我无法从这部分代码中看到,但我的猜测是您从 initstate 调用它。如果您想在创建小部件后立即调用此函数,请将其移至 onMapCreated。

    void onMapCreated(controller) {
       mapController = controller;
       moveCameraToUserLocation();
    }
    

    【讨论】:

      【解决方案2】:

      根据您对问题的描述,您似乎只是在地图加载时调用 animate 函数。


      我建议您创建一个按钮来处理和触发动画功能,并在点击时将相机移动到设备位置。

      以下代码 sn-p 使用ClipOval 按钮,在OnTap() 事件中,您可以调用该方法来获取设备当前位置,只要点击该按钮就会触发该方法。

      ClipOval(
         child: Material(
         color: Colors.green[100], // button color
         child: InkWell(
         splashColor: Colors.green, // inkwell color
         child: SizedBox(
         width: 56,
         height: 56,
         child: Icon(Icons.my_location),
         ),
         onTap: () {
      
          // Add methods here that will be called whenever the button is tapped 
      
          mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
          target: LatLng(_currentPosition.latitude, _currentPosition.longitude),
          zoom: 17.0)));
          setState(() {
          allMarkers.add(Marker(
            markerId: MarkerId('Current Position'),
            draggable: false,
            position:
                LatLng(_currentPosition.latitude, _currentPosition.longitude)));
              });
            },
          ),
        ),
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-18
        相关资源
        最近更新 更多