Home > database >  FLutter high accuracy with location package
FLutter high accuracy with location package

Time:02-12

For getting the user's location I am using two packages: location and geocoding. I use location to check if the user has provided location permission or not and to get the LocationData which carries the latitude and longitude.

But as far I have seen location does not provide the property called desiredAccuracy, which is much needed for my work.

  static void getCurrentLocation() async {
    Location location = new Location();
    bool _serviceEnabled;
    PermissionStatus _permissionGranted;
    LocationData _locationData;

    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }

    _locationData = await location.getLocation();
    double latitude = _locationData.latitude!;
    double longitude = _locationData.longitude!;
    List<geocoding.Placemark> placeMark =
        await geocoding.placemarkFromCoordinates(latitude, longitude);
    String country = placeMark.first.country!;
    String isoCountryCode = placeMark.first.isoCountryCode!;
    print("Country: $country and ISO Country Code: $isoCountryCode");

    print(_locationData);
  }

My code till now. Is it possible to get something like desiredAccuracy in Location? The only other solution for me would be to use geolocator and permission_handler packages which will require further configurations.

CodePudding user response:

I don't see why you don't want to use geolocator... you've already done the hard work. Here's how you get the location with desired accuracy

 location = await Geolocator.getCurrentPosition(
  forceAndroidLocationManager: true,
  desiredAccuracy: LocationAccuracy.best
).timeout(Duration(seconds: 20));

Here's how to check if service is enabled

var serviceEnabled = await Geolocator.isLocationServiceEnabled();

And here's how to check if permission is granted

    var permission = await Geolocator.checkPermission();

    if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.

Its clearly written in the documentation here geolocatordoc

  • Related