简体   繁体   English

Flutter - 无法找到如何在 Google Map 插件上获取相机的当前位置

[英]Flutter - Cannot find out how to get camera's current location on Google Map plugin

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).我正在使用Google Map 插件并发现在 map 上获取当前位置的问题(我的意思是相机的位置不是我的实时 GPS 位置)。

This is the map setup part.这是 map 设置部件。 map is a class property. map是 class 属性。

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.当我执行一个动作时, map.cameraTargetBounds.bounds返回 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.以防万一, GoogleMap.onCameraIdle()也没有提供CameraPosition作为参数。

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.它还会在相机空闲后将我的标记更新为新的 position。

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)
  GoogleMapController? mapController;

inside your GoogleMap widget use below code.在您的GoogleMap widget中使用以下代码。

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

here is your _getCurrentLocation function这是你的_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.全局粘贴以下代码以获取用户的当前 position。

use https://pub.dev/packages/geolocator for permission of location.使用https://pub.dev/packages/geolocator获得位置许可。

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 .以上commonAlertDialog是您在整个app中使用的dialog

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.一旦你设置了所有这些,它对你来说会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM