geolocator 5.1.5

  • Readme
  • Changelog
  • Example
  • Installing
  • 100

Flutter Geolocator Plugin #

pub package

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

BranchBuild Status
developBuild Status
masterBuild Status

Features #

  • Get the current location of the device;
  • Get the last known location;
  • Get continuous location updates;
  • Check if location services are enabled on the device;
  • Translate an address to geocoordinates and vice verse (a.k.a. Geocoding);
  • Calculate the distance (in meters) between two geocoordinates;
  • Check the availability of Google Play services (on Android only).

Note: The availability of the Google Play Services depends on your country. If your country doesn't support a connection with the Google Play Services, you need to try a VPN to establish a connection. For more information about how to work with Google Play Services visit the following link: https://developers.google.com/android/guides/overview

Usage #

To use this plugin, add geolocator as a dependency in your pubspec.yaml file. For example:

dependencies:
  geolocator: ^5.1.5

Paul Halliday wrote a nice introductory article on getting the user's location using the Geolocator plugin. If you are new to the plugin this would be a great place to get started.

NOTE: As of version 3.0.0 the geolocator plugin switched to the AndroidX version of the Android Support Libraries. This means you need to make sure your Android project is also upgraded to support AndroidX. Detailed instructions can be found here.

The TL;DR version is:

  1. Add the following to your "gradle.properties" file:
android.useAndroidX=true
android.enableJetifier=true
  1. Make sure you set the compileSdkVersion in your "android/app/build.gradle" file to 28:
android {
 compileSdkVersion 28

 ...
}
  1. Make sure you replace all the android. dependencies to their AndroidX counterparts (a full list can be found here: https://developer.android.com/jetpack/androidx/migrate).

API #

Geolocation #

To query the current location of the device simply make a call to the getCurrentPosition method:

import 'package:geolocator/geolocator.dart';

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

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(desiredAccuracy: LocationAccuracy.high);

To listen for location changes you can subscribe to the onPositionChanged stream. Supply an instance of the LocationOptions class to configure the desired accuracy and the minimum distance change (in meters) before updates are send to the application.

import 'package:geolocator/geolocator.dart';

var geolocator = Geolocator();
var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);

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

To check if location services are enabled you can call the checkGeolocationPermissionStatus method. This method returns a value of the GeolocationStatus enum indicating the availability of the location services on the device. Optionally you can specify if you want to test for GeolocationPermission.locationAlways or GeolocationPermission.locationWhenInUse (by default GeolocationPermission.location is used, which checks for either one of the previously mentioned permissions). Example usage:

import 'package:geolocator/geolocator.dart';

GeolocationStatus geolocationStatus  = await Geolocator().checkGeolocationPermissionStatus();

By default Geolocator will use FusedLocationProviderClient on Android when Google Play Services are available. It will fall back to LocationManager when it is not available. You can override the behaviour by setting forceAndroidLocationManager.

import 'package:geolocator/geolocator.dart';

Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true;
GeolocationStatus geolocationStatus  = await geolocator.checkGeolocationPermissionStatus();

To check if location services are enabled(Location Service(GPS) turned on) on the device checkGeolocationPermissionStatus will return disabled state if location service feature is disabled (or not available) on the device.

Geocoding #

To translate an address into latitude and longitude coordinates you can use the placemarkFromAddress method:

import 'package:geolocator/geolocator.dart';

List<Placemark> placemark = await Geolocator().placemarkFromAddress("Gronausestraat 710, Enschede");

If you want to translate latitude and longitude coordinates into an address you can use the placemarkFromCoordinates method:

import 'package:geolocator/geolocator.dart';

List<Placemark> placemark = await Geolocator().placemarkFromCoordinates(52.2165157, 6.9437819);

Both the placemarkFromAddress and placemarkFromCoordinates accept an optional localeIdentifier parameter. This paramter can be used to enforce the resulting placemark to be formatted (and translated) according to the specified locale. The localeIdentifier should be formatted using the syntax: [languageCode]_[countryCode]. Use the ISO 639-1 or ISO 639-2 standard for the language code and the 2 letter ISO 3166-1 standard for the country code. Some examples are:

Locale identifierDescription
enAll English speakers (will translate all attributes to English)
en_USEnglish speakers in the United States of America
en_UKEnglish speakers in the United Kingdom
nl_NLDutch speakers in The Netherlands
nl_BEDutch speakers in Belgium

Calculate distance #

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

ParameterTypeDescription
startLatitudedoubleLatitude of the start position
startLongitudedoubleLongitude of the start position
endLatitudedoubleLatitude of the destination position
endLongitudedoubleLongitude of the destination position
import 'package:geolocator/geolocator.dart';

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

See also the example project for a complete implementation.

Permissions #

Android #

On Android you'll need to add either the ACCESS_COARSE_LOCATION or the ACCESS_FINE_LOCATION permission to your Android Manifest. To do so open the AndroidManifest.xml file (located under android/app/src/main) and add one of the following two lines as direct children of the <manifest> tag:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

NOTE: Specifying the ACCESS_COARSE_LOCATION permission results in location updates with an accuracy approximately equivalant to a city block. More information can be found here.

iOS #

On iOS you'll need to add the NSLocationWhenInUseUsageDescription to your Info.plist file (located under ios/Runner/Base.lproj) in order to access the device's location. Simply open your Info.plist file and add the following:

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

If you would like to access the device's location when your App is running in the background, you should also add the NSLocationAlwaysAndWhenInUseUsageDescription (if your App support iOS 10 or earlier you should also add the key NSLocationAlwaysUsageDescription) key to your Info.plist file:

<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when open and in the background.</string>

Location accuracy #

The table below outlines the accuracy options per platform:

AndroidiOS
lowest500m3000m
low500m1000m
medium100 - 500m100m
high0 - 100m10m
best0 - 100m~0m
bestForNavigation0 - 100mOptimized for navigation

Issues #

Please file any issues, bugs or feature request as an issue on our GitHub page.

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. You can contact us at hello@baseflow.com

[5.1.5]

  • Android: Fixes bug where latitude and longitude are not returned as part of the placemark (thanks to @slightfood).

[5.1.4+2]

  • Return the heading on iOS correctly.

[5.1.4+1]

  • Downgrade the "meta" package to version 1.7.0 since pub.dev static code analysis reports errors.

[5.1.4]

  • Added support for Android 10’s background location permission;
  • Return heading as part of the position on iOS.

[5.1.3]

  • Added integration with public Bitrise CI project;
  • Fixed two analysis warnings;
  • Fixed a spelling error in docs.

[5.1.2]

  • Added new method to calculate bearing given two points.

[5.1.1+1]

  • Reverted the update of the 'meta' plugin as Flutter SDK depends on old version.

[5.1.1]

  • Updated dependency on 'meta' plugin to latest version.

[5.1.0]

  • Change geocoding results on Android to return multiple records;
  • Extended the example application;
  • Use the correct permission level enumeration;

Added documentation regarding AndroidX support. #

[5.0.1]

  • Make sure the stream channel is closed when Android activity is destroyed;
  • Allow developers to specify the permission level they want to use when requesting permissions on iOS.

[5.0.0]

  • Converted the iOS version from Swift to Objective-C, reducing the size of the final binary considerably, as well as solve some compatibility issues with other objective-c based plugins;
  • Fetch geocoding results on a separate thread not to slow down the main thread;
  • Bug fix where the current location could not be determined on non-GPS enabled phones;
  • Update to use latest gradle version.

[4.0.3]

  • Update to latest version of the Location Permissions plugin to solve a bug when permissions are sometimes not requested.

[4.0.2]

  • Bug fix on Android which causing the Reply already submitted error;
  • Updated location_permission plugin to version 2.0.0.

[4.0.1]

  • Updated to latest version of the Location Permissions plugin (1.1.0).

[4.0.0]

  • Overhauled the permissions system to make sure the plugin only depends on the location API. This means when using this version of the plugin Apple requires only entries for the NSLocationWhenInUseUsageDescription and/ or NSLocationAlwaysUsageDescription in the Info.plist.
  • breaking As part of the permission system overhaul, we removed the disabled permission status. To check if the location services are running you should call the isLocationServiceEnabled method. This means you can now also request permissions when the location services are disabled.

[3.0.1]

  • Updated dependencies on Permission Handler and Google API Availability to remove Kotlin dependency.

[3.0.0]

  • breaking Updated to support AndroidX;
  • Added API method isLocationServiceEnabled to check if location services are enabled or disabled
  • Removed method checkGeolocationStatus (marked deprecated in version 1.6.4);
  • Updated to latest version of Permission Handler plugin to solve some small issues on iOS;
  • Added Swift version number to podspec file;
  • Added ProGuard support for Android;
  • Updated static code analyses to confirm to latest recommendations from Flutter team.

[2.1.1]

  • Updated iOS code to Swift 4.2
  • Updated to latest version of the permission_handler plugin (v2.1.2)

[2.1.0]

  • Updated dependencies on Permission Handler and Google API Availability plugins.

[2.0.2]

  • Updated Gradle version

[2.0.1]

  • Bug fix where a null reference exception occurs because the timestamp of the Position could be null when fetching a Placemark using the placemarkFromAddress or placemarkFromCoordinates methods.

[2.0.0]

  • breaking The getPositionStream method now directly returns an instance of the Stream<Position> class, meaning there is no need to await the method before being able to access the stream;
  • breaking Arguments for the methods getCurrentPosition and getLastKnownPosition are now named optional parameters instead of positional optional parameters;
  • By default Geolocator will use FusedLocationProviderClient on Android when Google Play Services are available. It will fall back to LocationManager when it is not available. You can override the behaviour by setting Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true;
  • Allow developers to specify a desired interval for active location updates, in milliseconds (Android only).

[1.7.0]

  • Added timestamp to instances of the Position class indicating when the GPS fix was acquired;
  • Updated the dependency on the PermissionHandler to version >=2.0.0 <3.0.0.

[1.6.5]

  • Fixed bug on Android when not supplying a locale while using the Geocoding features.

[1.6.4]

  • Added support to supply a locale when using the placemarkFromAddress and placemarkFromCoordinates methods.
  • Deprecated the static method checkGeolocationStatus in favor of the instance method checkGeolocationPermissionStatus (the static version will be removed in version 2.0 of the Geolocator plugin).

[1.6.3]

  • Added feature to check the availability of Google Play services on the device (using the checkGooglePlayServicesAvailability method). This will allow developers to implement a more user friendly experience regarding the usage of Google Play services (for more information see the article Set Up Google Play Services);
  • Fixed the error 'List<dynamic>' is not a subtype of type 'Future<dynamic>' on Flutter 0.6.2 and higher (thanks @fawadkhanucp for reporting the issue and solution);
  • Fixed an error when calling the getCurrentPosition, getPositionStream, placemarkFromAddress and placemarkFromCoordinates from an Android background service (thanks @sestegra for reporting the issue and creating a pull-request).

[1.6.2]

  • Hot fix to solve cast exception

[1.6.1]

  • Fixed a bug which caused stationary location updates not to be streamed when using the new FusedLocationProviderClient on Android (thanks @audkar for the PR).

[1.6.0]

  • Use the Location Services (through the FusedLocationProviderClient) on Android if available, otherwise fallback to the LocationManager class;
  • Make sure that on Android the last know location is returned immediately on the stream when requesting location updates through the getPositionStream method;
  • Updated documentation on adding location permissions on Android.

[1.5.0]

  • It is now possible to check the location permissions using the checkGeolocationStatus method [ISSUE #51].
  • Improved the example App [ISSUE #54]
  • Solved a bug on Android causing a memory leak when you stop listening to the position stream.
  • breaking Solved a bug on Android where permissions could be requested more then once simultaniously [ISSUE #58]
  • Solved a bug on Android where requesting permissions twice would cause the App to crash [ISSUE #61]

Important:

To be able to correctly fix issue #58 we had to change the getPositionStream method into a async method. This means the signature of the method has been changed from:

Stream<Position> getPositionStream([LocationOptions locationOptions = const LocationOptions()])

to

Future<Stream<Position>> getPositionStream([LocationOptions locationOptions = const LocationOptions()]).

Meaning as a developer you'll now have to await the result of the method to get access to the actual stream.

[1.4.0]

  • Added feature to query the last known location that is stored on the device using the getLastKnownLocation method;
  • breaking Renamed the getPosition to getCurrentPosition;
  • Fixed bug where calling getCurrentPosition on Android resulted in returning the last known location;
  • breaking Renamed methods toPlacemark and fromPlacemark respectively to the, more meaningfull names, placemarkFromAddress and placemarkFromCoordinates;

[1.3.1]

  • Added support for iOS kCLLocationAccurayBestForNavigation (defaults to best when on Android).

[1.3.0]

  • Added the option to check the distance between two geocoordinates (using the distanceBetween method).

[1.2.2]

  • Make sure that an Android App using the plugin is informed when the platform stops transmitting location updates.

[1.2.1]

  • Added feature to throttle the amount of locations updates based on a supplied distance filter.

Important:

This introduces a breaking change since the signature of the getPositionStream has changed from getPositionStream(LocationAccuracy accuracy) to getPositionStream(LocationOptions locationOptions) .

  • Made some small changes to ensure the plugin no longer is depending on JAVA 8, meaning the plugin will run using the default Android configuration.

[1.2.0]

  • Added support to translate an address into geocoordinates and vice versa (a.k.a. Geocoding). See the README.md file for more information.

[1.1.2]

  • Fixed reported formatting issues

[1.1.1]

  • Fixed a warning generated by xCode when compiling the example project (see issue #28)
  • Fixed some warnings generated by Dart static code analyser, improving code quality

[1.1.0]

  • Introduced the option to supply a desired accuracy.

Important:

This introduces a breaking change, the getPosition and onPositionChanged properties have been replaced by methods (getPosition([LocationAccuracy desiredAccuracy = LocationAccuracy.Best]) and getPositionStream([LocationAccuracy desiredAccuracy = LocationAccuracy.Best]) respectively) accepting a parameter to indicate the desired accuracy.

[1.0.0]

  • Updated documentation
  • API defined stable

[0.0.2]

  • Solved problem with missing geolocator-Swift.h header file (see also issue Flutter#16049).

[0.0.1]

  • Initial release

example/README.md

geolocator_example #

Demonstrates how to use the geolocator plugin.

Getting Started #

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  geolocator: ^5.1.5

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:geolocator/geolocator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
99
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
100
Learn more about scoring.

We analyzed this package on Nov 15, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.6

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
google_api_availability ^2.0.1 2.0.1
location_permissions ^2.0.3 2.0.3
meta ^1.1.6 1.1.7 1.1.8
vector_math ^2.0.8 2.0.8
Transitive dependencies
collection 1.14.11 1.14.12
sky_engine 0.0.99
typed_data 1.1.6
Dev dependencies
flutter_test
pedantic ^1.7.0