Geolocator Package in flutter : How to implement it
Geolocator Flutter Package: The Flutter Geolocator plugin is a versatile geolocation package that provides easy access to platform-specific location services, like FusedLocationProviderClient or LocationManager on Android and CLLocationManager on iOS. It’s designed with both simplicity and feature-richness, enabling developers to access various location services easily.
Key features of the Flutter Geolocator include:
- Retrieve the last known location
- Fetch the current location of the device
- Receive continuous location updates
- Validate if location services are enabled
- Compute the distance (in meters) between two geo coordinates
With such a feature set, the Flutter Geolocator allows for a better user-specific experience and helps Flutter developers design immersive and dynamic applications.
url : https://pub.dev/packages/geolocator
Supported Platforms: Android, iOS, Linux, macOS, Web, Windows
Popularity: 5598 Likes
Setting up Flutter Geolocator
Integrating the Flutter Geolocator into your application is a pretty straightforward process. Let’s get started with it!
- First of all, add the geolocator plugin to the pubspec.yaml file in your Flutter project. It can be done as follows:
1dependencies:
2 flutter:
3 sdk: flutter
4 geolocator: ^10.1.0
Make sure to run flutter packages get in the terminal in your project directory or hit ‘Pub get’ in ‘pubspec.yaml’ file if you’re using Visual Studio Code or Android Studio.
- Now, that you’ve successfully installed the plugin, there come the necessary permissions that your Flutter app needs to access the user’s location. These permissions are different for Android and iOS, so let’s look at them one by one:
Android
For Android, you should add either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission. These permissions go into the ‘AndroidManifest.xml’ which is situated at android/app/src/main/AndroidManifest.xml.
Here’s how to do it:
1<!-- Either 'coarse' or 'fine' location permission is needed -->
2<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
iOS
For iOS, you will need to add either NSLocationWhenInUseUsageDescription, NSLocationAlwaysUsageDescription, or NSLocationAlwaysAndWhenInUseUsageDescription, along with the corresponding explanation string, this string will be displayed in the permission dialog shown to your user when the app requests access to the user’s location. These permissions go into Info.plist which is found at ios/Runner/Info.plist.
Here’s how to do it:
1<key>NSLocationWhenInUseUsageDescription</key>
2 <string>This app needs access to location when open.</string>
Once you’ve installed the plugin and set the necessary permissions, your Flutter application is ready to use the geolocation functionality powered by the Flutter Geolocator plugin.
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.
Using Flutter Geolocator: Accessing User’s Current Location
Accessing the user’s location is a fundamental aspect of many mobile applications. With Flutter Geolocator, obtaining the user’s physical location could not be simpler. It provides an easy-to-use method getCurrentPosition, which retrieves the device’s current location.
To ensure the location is retrieved accurately, ensure that the location services are enabled on the user’s device, and that your app has the necessary location permissions.
Below is a simplified code snippet showing how to acquire the current location:
1import 'package:geolocator/geolocator.dart';
2
3Future<Position> _determinePosition() async {
4 // Check if location services are enabled
5 bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
6 if (!serviceEnabled) {
7 // Location services are not enabled return an error message
8 return Future.error('Location services are disabled.');
9 }
10
11 // Check location permissions
12 LocationPermission permission = await Geolocator.checkPermission();
13 if (permission == LocationPermission.denied) {
14 permission = await Geolocator.requestPermission();
15 if (permission == LocationPermission.denied) {
16 return Future.error('Location permissions are denied');
17 }
18 }
19
20 if (permission == LocationPermission.deniedForever) {
21 return Future.error(
22 'Location permissions are permanently denied, we cannot request permissions.');
23 }
24
25 // If permissions are granted, return the current location
26 return await Geolocator.getCurrentPosition();
27}
First, it checks if the location services are enabled on the device, then it verifies the location permissions and finally fetches the current location if everything is set right.
The above method _determinePosition can then be used to get the latitude and longitude coordinates of the user’s location, as shown in the following example:
1void main() {
2 runApp(MyApp());
3}
4
5class MyApp extends StatelessWidget {
6 @override
7 Widget build(BuildContext context) {
8 return MaterialApp(
9 home: Scaffold(
10 body: FutureBuilder(
11 future: _determinePosition(),
12 builder: (BuildContext context, AsyncSnapshot<Position> snapshot) {
13 if (snapshot.hasData) {
14 return Center(
15 child: Text(
16 'Your current location:\nLatitude: ${snapshot.data!.latitude}, Longitude: ${snapshot.data!.longitude}'),
17 );
18 } else if (snapshot.hasError) {
19 return Text('Error: ${snapshot.error}');
20 }
21
22 // The connection state is still ongoing
23 return CircularProgressIndicator();
24 },
25 ),
26 ),
27 );
28 }
29}
In this example, we use the FutureBuilder widget that allows our Flutter app to be notified when Future<Position>
completes and an AsyncSnapshot is available. It leads to an asynchronous computation of the latitude and longitude of the user’s current location.
Flutter Geolocator: Distance Calculations
Calculating distances between two geographical points is pivotal while developing apps leveraging location data. In this section, we will provide a detailed guideline on accomplishing this task with Flutter’s geolocator plugin.
The geolocator plugin provides a utility method distanceBetween to calculate the distance in meters between two different geographic coordinates. It accepts four parameters representing the latitude and longitude coordinates of the two points.
Here’s a simple Flutter code snippet demonstrating the usage:
1import 'package:geolocator/geolocator.dart';
2
3void calculateDistance() {
4 double startLatitude = 52.2165157;
5 double startLongitude = 6.9437819;
6 double endLatitude = 52.3546274;
7 double endLongitude = 4.8285838;
8
9 double distanceInMeters = Geolocator.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude);
10
11 print('The distance between these points is $distanceInMeters meters.');
12}
In this example, we import the geolocator package and then define the calculateDistance function. Inside this function, we use the Geolocator.distanceBetween method to calculate the distance between the starting and ending points specified by their respective latitude and longitude coordinates.
This functionality enables numerous interesting features within your Flutter app such as filtering entities based on their proximity to the user’s current location, creating location-based recommendations, or calculating travel distances.
Get current location in Flutter
Flutter Geolocator FAQs
How to Get Current Location in Flutter — Geolocator
Setting up The Project. To begin, we must add the required dependencies, the geolocator and geocoding packages to your pubspec. …
Handle Location Services and Permissions. We must have the user’s permission to get the user’s location. …
Get the User’s Latitude and Longitude.
Flutter Geolocator Plugin
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;
To create a Flutter app, which can access the location of the device. We need to add the geolocator inside the dependencies of the . yaml file of your app. After adding the dependencies, we need to run the command ‘flutter pub get’ that fetches all the packages defined.
Check Also : How to get Element at specific Index from List in Dart
Read more updates related to flutter at flutterfever.com.