Home > Software engineering >  Flutter - Cannot find out how to get camera's current location on Google Map plugin
Flutter - Cannot find out how to get camera's current location on Google Map plugin

Time:08-10

I'm using Google Map plugin and found a problem to get current location on the map (I mean camera's location not my live GPS location).

This is the map setup part. map is a class property.

map = GoogleMap(
   mapType : MapType.normal,
   initialCameraPosition : CameraPosition(
      target: LatLng(0, 0),
      zoom: 15
   ),
   onMapCreated : (GoogleMapController controller){
      completer.complete(controller);
   },
)

When I execute an action, map.cameraTargetBounds.bounds returns null. I'm not getting it on moving camera. Just in case for at least a workaround, GoogleMap.onCameraIdle() also provide no CameraPosition as parameter.

CodePudding user response:

Set<Marker> _markers = {};
CameraPosition? cameraPosition;

.....


Align(
  alignment: Alignment.topCenter,
  child: GoogleMap(
    onMapCreated: _onMapCreated,
    myLocationButtonEnabled: true,
    markers: _markers,
    initialCameraPosition: CameraPosition(
        target: LatLng(appState.masterData?.latitude ?? 0.0,
            appState.masterData?.longitude ?? 0.0),
        zoom: 15.0),
    onCameraMove: (CameraPosition position) {
      print("pos : $position");
      setState(() {
        cameraPosition = position;
      });
    },
    onCameraIdle: () {
      setState(() {
        _markers.clear();
        _markers.add(
          Marker(
            markerId: const MarkerId('adasda'),
            position:
                cameraPosition?.target ?? const LatLng(0.0, 0.0),
            icon: BitmapDescriptor.defaultMarkerWithHue(270),
          ),
        );
      });
    },
  ),
),

and it also update my marker to the new position after camera idle.

here the logs

I/flutter (10263): pos : CameraPosition(bearing: 0.0, target: LatLng(-6.096001032024194, 106.82576134800911), tilt: 0.0, zoom: 15.0)
I/Counters(10263): exceeded sample count in FrameTime
I/flutter (10263): pos : CameraPosition(bearing: 0.0, target: LatLng(-6.096001032024194, 106.82576134800911), tilt: 0.0, zoom: 15.0)
I/flutter (10263): pos : CameraPosition(bearing: 0.0, target: LatLng(-6.095937356390648, 106.82576771825552), tilt: 0.0, zoom: 15.0)
2
I/Counters(10263): exceeded sample count in FrameTime
I/flutter (10263): pos : CameraPosition(bearing: 0.0, target: LatLng(-6.095937356390648, 106.82576771825552), tilt: 0.0, zoom: 15.0)
I/flutter (10263): pos : CameraPosition(bearing: 0.0, target: LatLng(-6.095929355263389, 106.82576905936001), tilt: 0.0, zoom: 15.0)
I/flutter (10263): pos : CameraPosition(bearing: 0.0, target: LatLng(-6.095866346382027, 106.82578079402448), tilt: 0.0, zoom: 15.0)

CodePudding user response:

  GoogleMapController? mapController;

inside your GoogleMap widget use below code.

 onMapCreated: (GoogleMapController controller) {
              completer.complete(controller);
              mapController = controller;
              _getCurrentLocation();
      },

here is your _getCurrentLocation function

_

getCurrentLocation() async {
    await determinePosition(context).then((Position position) async {
      setState(() {
        mapController?.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: LatLng(position.latitude, position.longitude),
              zoom: 10.0,
            ),
          ),
        );
      });
      // await _getAddress();
    }).catchError((e) {});
  }

paste below code globally to get current position of user.

use https://pub.dev/packages/geolocator for permission of location.

Future<Position> determinePosition({BuildContext? context}) async {
  bool serviceEnabled;
  LocationPermission permission;
  print(await Geolocator.isLocationServiceEnabled());
  print(await Permission.locationWhenInUse.status);
  print(await Permission.locationAlways.status);
  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    if (context != null) {
      commonAlertDialog(
          context: context,
          message: "Mobile GPS/Location is not granted please allow permission from your setting for better app performance.",
          cancelCall: () {
            Get.back();
            Get.back();
          },
          okCall: () async {
            Get.back();
            permissionAsked.value = true;
            await Geolocator.openLocationSettings();
          });
    }
    // return showSnackBar(message: 'Location services are disabled.');
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      return showSnackBar(message: 'Location services are disabled.');
      return Future.error('Location permissions are denied');
    }
  }

  if (permission == LocationPermission.deniedForever) {
    if (context != null) {
      return commonAlertDialog(
          context: context,
          message: "Location permission not granted please allow permission from your setting for better app performance.",
          cancelCall: () {
            Get.back();
          },
          okCall: () async {
            Get.back();
            permissionAsked.value = true;
            await Geolocator.openAppSettings();
          });
    }
    return Future.error('Location permissions are permanently denied, we cannot request permissions.');
  }

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition();
}

above commonAlertDialog is your dialog that you are using in whole app.

I know this is long process but it helps you in most case scenario. And once you set all this it'll be easier for you.

  • Related