如何以编程方式获取当前用户位置以在颤振中加载到地图上

How to programatically getting current users location to load on a map in flutter

请帮忙。我试图让 initialCameraPosition 以编程方式在地图上显示用户的当前位置。我不想硬编码。 我有一个 getCurrentLocation 方法,但我似乎无法将结果(它的纬度和经度)用作地图的 initialCameraPosition 的纬度和经度。

getCurrentLocation 方法是

Future<Position> getCurrentPosition() async {
Position position = await Geolocator()
    .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
return position;

}

Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Colors.white,
  body: Stack(
    children: <Widget>[
      GoogleMap(
        initialCameraPosition:
            CameraPosition(target: LatLng(9.0765, 7.3986), zoom: 17),//these coordinates should not be hard coded
        onMapCreated: _onMapCreated,
        myLocationEnabled: true,
        mapType: MapType.normal,
        markers: _marker,
      ),}

等待加载用户当前位置;

1 从 init() 中点击 getCurrentPosition() 就像

Position position;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getCurrentPosition()
  }

  getCurrentPosition() async 
    {
    position = await Geolocator()
            .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

    setState((){});
     
    }

2。现在你构建函数将是这样的:

Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: position==null?CircularProgressIndicator(): Stack(
            children: <Widget>[
        GoogleMap( initialCameraPosition: CameraPosition(target:position.getLatLng, zoom: 17),

          onMapCreated: _onMapCreated,
          myLocationEnabled: true,
          mapType: MapType.normal,
          markers: _marker,

    )]));

  }