如何使用 CameraPosition 獲取當前位置?
這是我的代碼,我需要獲取當前位置,但不知道如何實作......
@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
我可以得到當前位置然后放入 inottarget: LatLng(-42.883187304882235, 147.32749945640126)嗎?
uj5u.com熱心網友回復:
為什么將 CameraPosition 定義為 static const?
請嘗試定義默認的 CameraPosition 并像這樣在 getCurrentPosition() 函式中更改它。
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);
},
),
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473385.html
