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

Issue

Please help. I am trying to get the initialCameraPosition to programmatically display the current location of a user on a map. I don’t want to hard code it.
I have a getCurrentLocation method but I can’t seem to use the result (its lat and lon) as the latitude and longitude of the initialCameraPosition of the Map.

the getCurrentLocation method is

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

Solution

Just wait to load user current location ;

1 hit getCurrentPosition() from init() like

Position position;

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

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

    setState((){});
     
    }

2. Now you build function will be like:

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,

    )]));

  }

Answered By – Deepak Ror

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *