Geolocator

Flutter Geolocator Plugin

pub package Build status style: effective dart codecov

A Flutter geolocation plugin which provides easy access to platform specific location services (FusedLocationProviderClient or if not available the LocationManager on Android and CLLocationManager on iOS).


Features

  • Get the last known location;
  • Get the current location of the device;
  • Get continuous location updates;
  • Check if location services are enabled on the device;
  • Calculate the distance (in meters) between two geocoordinates;
  • Calculate the bearing between two geocoordinates;
IMPORTANT:
Version 7.0.0 of the geolocator plugin contains several breaking changes, for a complete overview please have a look at the Breaking changes in 7.0.0 wiki page.
Starting from version 6.0.0 the geocoding features (placemarkFromAddress and placemarkFromCoordinates) are no longer part of the geolocator plugin. We have moved these features to their own plugin: geocoding. This new plugin is an improved version of the old methods.


Usage

To add the geolocator to your Flutter application read the install instructions. Below are some Android and iOS specifics that are required for the geolocator to work correctly.

Android

iOS

macOS

Web

Windows


Example

The code below shows an example on how to acquire the current position of the device, including checking if the location services are enabled and checking / requesting permission to access the position of the device:

import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the 
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  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.
      return Future.error('Location permissions are denied');
    }
  }
  
  if (permission == LocationPermission.deniedForever) {
    // Permissions are denied forever, handle appropriately. 
    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();
}


API


Geolocation


Current location

To query the current location of the device simply make a call to the getCurrentPosition method. You can finetune the results by specifying the following parameters:

  • desiredAccuracy: the accuracy of the location data that your app wants to receive;
  • timeLimit: the maximum amount of time allowed to acquire the current location. When the time limit is passed a TimeOutException will be thrown and the call will be cancelled. By default no limit is configured.
import 'package:geolocator/geolocator.dart';

Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);


Last known location

To query the last known location retrieved stored on the device you can use the getLastKnownPosition method (note that this can result in a null value when no location details are available):

import 'package:geolocator/geolocator.dart';

Position? position = await Geolocator.getLastKnownPosition();


Listen to location updates

To listen for location changes you can call the getPositionStream to receive stream you can listen to and receive position updates. You can finetune the results by specifying the following parameters:

  • accuracy: the accuracy of the location data that your app wants to receive;
  • distanceFilter: the minimum distance (measured in meters) a device must move horizontally before an update event is generated;
  • timeLimit: the maximum amount of time allowed between location updates. When the time limit is passed a TimeOutException will be thrown and the stream will be cancelled. By default no limit is configured.
import 'package:geolocator/geolocator.dart';

final LocationSettings locationSettings = LocationSettings(
  accuracy: LocationAccuracy.high,
  distanceFilter: 100,
);
StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
    (Position? position) {
        print(position == null ? 'Unknown' : '${position.latitude.toString()}, ${position.longitude.toString()}');
    });

In certain situation it is necessary to specify some platform specific settings. This can be accomplished using the platform specific AndroidSettings or AppleSettings classes. When using a platform specific class, the platform specific package must be imported as well. For example:

import 'package:geolocator/geolocator.dart';
import 'package:geolocator_apple/geolocator_apple.dart';
import 'package:geolocator_android/geolocator_android.dart';

late LocationSettings locationSettings;

if (defaultTargetPlatform == TargetPlatform.android) {
  locationSettings = AndroidSettings(
    accuracy: LocationAccuracy.high,
    distanceFilter: 100,
    forceLocationManager: true,
    intervalDuration: const Duration(seconds: 10),
    //(Optional) Set foreground notification config to keep the app alive 
    //when going to the background
    foregroundNotificationConfig: const ForegroundNotificationConfig(
        notificationText:
        "Example app will continue to receive your location even when you aren't using it",
        notificationTitle: "Running in Background",
        enableWakeLock: true,
    )
  );
} else if (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS) {
  locationSettings = AppleSettings(
    accuracy: LocationAccuracy.high,
    activityType: ActivityType.fitness,
    distanceFilter: 100,
    pauseLocationUpdatesAutomatically: true,
    // Only set to true if our app will be started up in the background.
    showBackgroundLocationIndicator: false,
  );
} else {
    locationSettings = LocationSettings(
    accuracy: LocationAccuracy.high,
    distanceFilter: 100,
  );
}

StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
    (Position? position) {
        print(position == null ? 'Unknown' : '${position.latitude.toString()}, ${position.longitude.toString()}');
    });


Location accuracy (Android and iOS 14+ only)

To query if a user enabled Approximate location fetching or Precise location fetching, you can call the Geolocator().getLocationAccuracy() method. This will return a Future<LocationAccuracyStatus>, which when completed contains a LocationAccuracyStatus.reduced if the user has enabled Approximate location fetching or LocationAccuracyStatus.precise if the user has enabled Precise location fetching. When calling getLocationAccuracy before the user has given permission, the method will return LocationAccuracyStatus.reduced by default. On iOS 13 or below, the method getLocationAccuracy will always return LocationAccuracyStatus.precise, since that is the default value for iOS 13 and below.

import 'package:geolocator/geolocator.dart';

var accuracy = await Geolocator.getLocationAccuracy();


Location service information

To check if location services are enabled you can call the isLocationServiceEnabled method:

import 'package:geolocator/geolocator.dart';

bool isLocationServiceEnabled  = await Geolocator.isLocationServiceEnabled();

To listen for service status changes you can call the getServiceStatusStream. This will return a Stream<ServiceStatus> which can be listened to, to receive location service status updates.

import 'package:geolocator/geolocator.dart';

StreamSubscription<ServiceStatus> serviceStatusStream = Geolocator.getServiceStatusStream().listen(
    (ServiceStatus status) {
        print(status);
    });


Permissions

When using the web platform, the checkPermission method will return the LocationPermission.denied status, when the browser doesn't support the JavaScript Permissions API. Nevertheless, the getCurrentPosition and getPositionStream methods can still be used on the web platform.

If you want to check if the user already granted permissions to acquire the device's location you can make a call to the checkPermission method:

import 'package:geolocator/geolocator.dart';

LocationPermission permission = await Geolocator.checkPermission();

If you want to request permission to access the device's location you can call the requestPermission method:

import 'package:geolocator/geolocator.dart';

LocationPermission permission = await Geolocator.requestPermission();

Possible results from the checkPermission and requestPermission methods are:

PermissionDescriptiondeniedPermission to access the device's location is denied by the user. You are free to request permission again (this is also the initial permission state).deniedForeverPermission to access the device's location is permanently denied. When requesting permissions the permission dialog will not be shown until the user updates the permission in the App settings.whileInUsePermission to access the device's location is allowed only while the App is in use.alwaysPermission to access the device's location is allowed even when the App is running in the background.

Note: Android can only return whileInUsealways or denied when checking permissions. Due to limitations on the Android OS it is not possible to determine if permissions are denied permanently when checking permissions. Using a workaround the geolocator is only able to do so as a result of the requestPermission method. More information can be found in our wiki.


Settings

In some cases it is necessary to ask the user and update their device settings. For example when the user initially permanently denied permissions to access the device's location or if the location services are not enabled (and, on Android, automatic resolution didn't work). In these cases you can use the openAppSettings or openLocationSettings methods to immediately redirect the user to the device's settings page.

On Android the openAppSettings method will redirect the user to the App specific settings where the user can update necessary permissions. The openLocationSettings method will redirect the user to the location settings where the user can enable/ disable the location services.

On iOS we are not allowed to open specific setting pages so both methods will redirect the user to the Settings App from where the user can navigate to the correct settings category to update permissions or enable/ disable the location services.

import 'package:geolocator/geolocator.dart';

await Geolocator.openAppSettings();
await Geolocator.openLocationSettings();


Utility methods

To calculate the distance (in meters) between two geocoordinates you can use the distanceBetween method. The distanceBetween method takes four parameters:

ParameterTypeDescriptionstartLatitudedoubleLatitude of the start positionstartLongitudedoubleLongitude of the start positionendLatitudedoubleLatitude of the destination positionendLongitudedoubleLongitude of the destination position

import 'package:geolocator/geolocator.dart';

double distanceInMeters = Geolocator.distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);

If you want to calculate the bearing between two geocoordinates you can use the bearingBetween method. The bearingBetween method also takes four parameters:

ParameterTypeDescriptionstartLatitudedoubleLatitude of the start positionstartLongitudedoubleLongitude of the start positionendLatitudedoubleLatitude of the destination positionendLongitudedoubleLongitude of the destination position

import 'package:geolocator/geolocator.dart';

double bearing = Geolocator.bearingBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);


Location accuracy

The table below outlines the accuracy options per platform:

AndroidiOSlowest500m3000mlow500m1000mmedium100 - 500m100mhigh0 - 100m10mbest0 - 100m~0mbestForNavigation0 - 100mOptimized for navigation


Issues

Please file any issues, bugs or feature requests as an issue on our GitHub page. Commercial support is available, you can contact us at hello@baseflow.com.


Want to contribute

If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug or adding a cool new feature), please carefully review our contribution guide and send us your pull request.


Author

This Geolocator plugin for Flutter is developed by Baseflow.


GitHub


View GitHub


Description of the image

Related Posts