Home > database >  how to use CameraPosition get current position?
how to use CameraPosition get current position?

Time:05-11

how to use CameraPosition get current position?

this is my code, I need to get the current position, but have no idea to realize...

@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);
          },
        ),

I don't know why I cannot put currentPostion into target when I got the position.

I tried to used this target: currentPostion, but I got the error

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

Could I got current position then put inot target: LatLng(-42.883187304882235, 147.32749945640126)??

CodePudding user response:

Why do you define CameraPosition as static const?

Please try to define default CameraPosition and change it in getCurrentPosition() function like this.

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);
  },
),
  • Related