0

请帮忙。我试图让 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,
      ),}
4

1 回答 1

0

等待加载用户当前位置;

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,

    )]));

  }
于 2020-06-28T06:30:15.340 回答