如何使用camerposition获取当前位置?



如何使用camerposition获取当前位置?

这是我的代码,我需要得到当前的位置,但不知道实现…

@override
void initState() {
super.initState();
getCurrentPostion();
}
getCurrentPostion() async {
//get CurrentPosition
var position = await GeolocatorPlatform.instance.getCurrentPosition();
setState(() {
currentPostion = LatLng(position.latitude, position.longitude);
});
}
static const CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(-42.883187304882235, 147.32749945640126),
zoom: 10,
);

GoogleMap(
initialCameraPosition: _kGooglePlex,
mapType: MapType.normal,
myLocationButtonEnabled: true,
myLocationEnabled: true,
markers: Set<Marker>.of(_markers),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),

我不知道为什么当我得到这个职位时,我不能把currentPostion放进target

我试图使用这个target: currentPostion,但我得到了错误

The instance member 'currentPostion' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression

我可以得到当前的位置,然后不放target: LatLng(-42.883187304882235, 147.32749945640126)吗??

为什么要将camerposition定义为静态const?

请尝试在getCurrentPosition()函数中定义默认的camerposition并像这样更改它。

CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(-42.883187304882235, 147.32749945640126),
zoom: 10,
);
@override
void initState() {
super.initState();
getCurrentPostion();
}
getCurrentPostion() async {
//get CurrentPosition
var position = await GeolocatorPlatform.instance.getCurrentPosition();
setState(() {
currentPostion = LatLng(position.latitude, position.longitude);
_kGooglePlex = CameraPosition(
target: currentPostion,
zoom: 10,
);
});
}

GoogleMap(
initialCameraPosition: _kGooglePlex,
mapType: MapType.normal,
myLocationButtonEnabled: true,
myLocationEnabled: true,
markers: Set<Marker>.of(_markers),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),

最新更新