Search code examples
fluttergoogle-mapsgeolocationgoogle-geolocationgoogle-maps-flutter

Current location on the google maps (Flutter)


I try to get current location my device and use it in initialCameraPosition,

The function is executed and I get the coordinates and set it in _currentPosition

After starting the screen i have an error:

LateError (LateInitializationError: Field 'currentPosition' has not been initialized.)

I think, map is created faster than the data is written to the variable, but i dont know how it fix.

Thanks fo help or advice how make code is correct


import 'package:flutter/material.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';

import 'package:geolocator/geolocator.dart';

class UserMapInfo extends StatefulWidget {
  const UserMapInfo({Key? key}) : super(key: key);

  @override
  State<UserMapInfo> createState() => _UserMapInfoState();
}

class _UserMapInfoState extends State<UserMapInfo> {
  late GoogleMapController mapController;

  late LatLng _currentPosition;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _currentPosition,
          zoom: 16.0,
        ),
      ),
    );
  }
}

Update

I try to use

LatLng? _currentPosition;

and add test coordinates

LatLng basePosition = LatLng(56.324293441187315, 38.13961947281509);

and add "null check"

my code


class _UserMapInfoState extends State<UserMapInfo> {
  
  late GoogleMapController mapController;

  // late LatLng currentPosition;

  LatLng? _currentPosition;

  LatLng basePosition = LatLng(56.324293441187315, 38.13961947281509);

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _currentPosition ?? basePosition,
          zoom: 16.0,
        ),
      ),
    );
  }
}

And when my map is open, use LatLng basePosition ((( this is not what i need

I try other null check


initialCameraPosition: CameraPosition(
          target: _currentPosition!,
          zoom: 16.0,
        ),

ERROR again

_CastError (Null check operator used on a null value)

Thanks! Good solution!

And i`m add "null check" there

final code


import 'package:flutter/material.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';

import 'package:geolocator/geolocator.dart';

class UserMapInfo extends StatefulWidget {
  const UserMapInfo({Key? key}) : super(key: key);

  @override
  State<UserMapInfo> createState() => _UserMapInfoState();
}

class _UserMapInfoState extends State<UserMapInfo> {
  late GoogleMapController mapController;

  LatLng? _currentPosition;

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
      _isLoading = false;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                target: _currentPosition!,
                zoom: 16.0,
              ),
            ),
    );
  }
}



Solution

  • Try this:

    class _UserMapInfoState extends State<UserMapInfo> {
      
      late GoogleMapController mapController;
    
      LatLng? _currentPosition;
      bool _isLoading = true;
    
      @override
      void initState() {
        super.initState();
        getLocation();
      }
    
      getLocation() async {
        LocationPermission permission;
        permission = await Geolocator.requestPermission();
    
        Position position = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.high);
        double lat = position.latitude;
        double long = position.longitude;
    
        LatLng location = LatLng(lat, long);
    
        setState(() {
          _currentPosition = location;
          _isLoading = false;
        });
      }
    
      void _onMapCreated(GoogleMapController controller) {
        mapController = controller;
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Map'),
          ),
          body: _isLoading ? 
          Center(child:CircularProgressIndicator()) : 
          GoogleMap(
            onMapCreated: _onMapCreated,
            initialCameraPosition: CameraPosition(
              target: _currentPosition,
              zoom: 16.0,
            ),
          ),
        );
      }
    }