Google Maps Current User Location - Flutter

Viewed 6928

I am trying to get the user's current location from Google Maps but I am getting an exception in return which I can't seem to understand why it's happening. The app is simple - get the user's current location, and then zoom the camera onto that location. That's it.

I am going to attach my code and the exception message. The strange thing is that I am getting my LatLng correctly as you can see in the exception message, so why is the camera not pointing to that location?

class Map extends StatefulWidget {
  @override
  _MapState createState() => _MapState();
}

class _MapState extends State<Map> {

  LatLng currentLatLng;
  Completer<GoogleMapController> _controller = Completer();


  @override
  void initState(){
    super.initState();
    Geolocator.getCurrentPosition().then((currLocation){
      setState((){
        currentLatLng = new LatLng(currLocation.latitude, currLocation.longitude);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    print("Current Location --------> " + currentLatLng.latitude.toString() + " " + currentLatLng.longitude.toString());
    return MaterialApp(
      home: new Scaffold(
        body: GoogleMap(
          mapType: MapType.normal,
          initialCameraPosition: CameraPosition(target: currentLatLng),
          onMapCreated: (GoogleMapController controller) {
            _controller.complete(controller);
          },
        ),
      ),
    );
  }
}

Exception Message

note - I am using 'geolocator' and 'google_maps_flutter' from pub.dev - all latest versions.

1 Answers

This is async programming. currentLatLng is null until getCurrentPosition calls it's callback, so you can't just do this:

initialCameraPosition: CameraPosition(target: currentLatLng)

because, as you error shows, currentLatLng is null.

Your two options are:

  1. Set the map to a default position that you define and then update the position using the mapcontroller when getCurrentPosition completes.

  2. Show a loader while currentLatLng is null, and when it's no longer null, show your map.

Here's an example for 2

    return MaterialApp(
      home: new Scaffold(
        body: currentLatLng == null ? Center(child:CircularProgressIndicator()) : GoogleMap(
          mapType: MapType.normal,
          initialCameraPosition: CameraPosition(target: currentLatLng),
          onMapCreated: (GoogleMapController controller) {
            _controller.complete(controller);
          },
        ),
      ),
    );
Related