Flutter:如何设置谷歌地图相机的动画



我正在尝试构建一个加载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(),
...

根据您对问题的描述,看起来您只是在加载映射时调用animate函数。


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

下面的代码片段使用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)));
});
},
),
),
)

可能是在创建映射之前调用moveCameraToUserLocation函数。从这部分代码中,我无法确定何时调用该函数,但我猜测是从initstate调用它。如果您想在创建小部件后立即调用此函数,请将其移动到onMapCreated。

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

最新更新