In the digital era, utilizing location services has become critical for many applications to provide user-specific content and improve app interactivity. While creating mobile applications with Flutter, how do we harness these services? How do we locate the user's current position or continuously track their location updates? Here comes the Flutter Geolocator plugin to our rescue!
This blog post dives deep into this exceptional Flutter plugin and explores how to use it effectively to enhance your app's geolocation functionality. We'll explore everything from setting up the Flutter Geolocator package in your Flutter application to accessing the user's current location, managing location permissions, and receiving continuous location updates. So, without further ado, let's get started!
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:
With such a feature set, the Flutter Geolocator allows for a better user-specific experience and helps Flutter developers design immersive and dynamic applications. Using keywords from the official package README file is programming friendly, keeping the context and meaning unaltered and explaining the term in a non-technical friendly language readable for developers.
Integrating the Flutter Geolocator into your application is a pretty straightforward process. Let's get started with it!
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.
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" />
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.
All the necessary permissions and dependencies are based on the official Flutter Geolocator plugin's README file. It's essential to check the recent version of the geolocator plugin, as the version in this post might have been updated.
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}
This code follows the official Flutter Geolocator plugin's README document[^1^]. 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 completes and an AsyncSnapshot is available. It leads to an asynchronous computation of the latitude and longitude of the user's current location.
The Flutter Geolocator plugin provides several location services that allow your application to interact more suitably according to the user's location. Let's discuss some of them.
To track the user's location continuously, you can use the getPositionStream method, which provides a live feed of the user's location data. A great feature is that you can fine-tune the results specifying parameters like accuracy, distanceFilter, and timeInterval. Here's a method to listen to location changes:
1import 'package:geolocator/geolocator.dart'; 2 3void getLocationUpdates() { 4 final locationSettings = LocationSettings(accuracy: LocationAccuracy.high, distanceFilter: 100); 5 StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen( 6 (Position position) { 7 print(position == null ? 'Unknown' : '${position.latitude}, ${position.longitude}'); 8 } 9 ); 10}
This method initializes location settings with high accuracy and a distance filter of 100 meters. It then listens to getPositionStream, which continuously updates the user's location. The new latitude and longitude coordinates are printed each time a positional update is received.
Before you fetch any location data, checking if location services are enabled on the user's device is good practice. Flutter Geolocator provides the isLocationServiceEnabled method, which returns a Future flag that notifies if the location services are activated.
1import 'package:geolocator/geolocator.dart'; 2 3void checkIfLocationServiceIsEnabled() async { 4 bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled(); 5 if (isLocationServiceEnabled) { 6 // You can fetch location data here or alert the user that location services are turned on. 7 print('Location services are enabled'); 8 } else { 9 // You could try to prompt the user to turn on location services here or handle it differently. 10 print('Location services are disabled'); 11 } 12}
These are just a few ways to take advantage of the location services with Flutter Geolocator. Given its versatility, there are many more functionalities whose implementation will noticeably depend on the structure and requirements of your application.
Using the geolocation services entails utilizing private user data (i.e., the user's current location). Hence, managing location permissions appropriately is necessary to access this data while ensuring security and trust with your users. Thankfully, the Flutter Geolocator makes managing permissions relatively easy too.
Before requesting any location data, always check the status of location permissions. If they're granted, you're good to go. If they're denied, you'll need to request the permissions first.
Here's how you check the location permission:
1import 'package:geolocator/geolocator.dart'; 2 3void checkLocationPermission() async { 4 LocationPermission permission = await Geolocator.checkPermission(); 5 if (permission == LocationPermission.denied) { 6 // Permissions are denied. 7 print("Location permissions are denied"); 8 } else if (permission == LocationPermission.deniedForever) { 9 // Permissions are denied forever. 10 print("Location permissions are permanently denied"); 11 } else { 12 // Permissions are granted (either can be whileInUse, always, restricted). 13 print("Location permissions are granted"); 14 } 15}
If the permissions are denied, you can request them. The Flutter Geolocator provides the requestPermission method to request location permissions.
Here's how you request location permission:
1import 'package:geolocator/geolocator.dart'; 2 3void requestLocationPermission() async { 4 LocationPermission permission = await Geolocator.checkPermission(); 5 if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) { 6 // Permissions are denied or denied forever, let's request it! 7 permission = await Geolocator.requestPermission(); 8 if (permission == LocationPermission.denied) { 9 print("Location permissions are still denied"); 10 } else if (permission == LocationPermission.deniedForever) { 11 print("Location permissions are permanently denied"); 12 } else { 13 // Permissions are granted (either can be whileInUse, always, restricted). 14 print("Location permissions are granted after requesting"); 15 } 16 } 17}
It's important to note that almost all geolocation operations implemented in Flutter Geolocator will automatically request permissions if they have yet to be granted.
One of the exciting features of the Flutter Geolocator plugin is the ability to receive location updates. This offers utility for various use-cases like tracking a user's movements in a vehicle, real-time location updates of a friend on a map, and more.
The Geolocator provides an easy-to-use getPositionStream method which listens to the stream of locations as the device moves and the location changes. Here is an example of using this function:
1StreamSubscription<Position> _positionStream; 2 3void getLocationUpdates() { 4 final LocationSettings locationSettings = LocationSettings( 5 accuracy: LocationAccuracy.high, 6 distanceFilter: 10, 7 ); 8 9 _positionStream = Geolocator.getPositionStream(locationSettings: locationSettings) 10 .listen((Position position) { 11 print('Latitude: ${position.latitude}, Longitude: ${position.longitude}'); 12 }); 13}
In this example, we accurately defined the location settings and set the distance filter to 10 meters. Now, every time the device moves more than 10 meters, our listener will return to the current position of the device (latitude and longitude).
At times, stop receiving location updates. You can use the cancel method on your stream subscription in such cases. Here's how to do it:
1void stopListening() { 2 _positionStream?.cancel(); 3}
Remember when you're done with receiving updates, always cancel the stream subscription to prevent memory leaks.
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.
While working with geolocation in Flutter, you may encounter some common issues or errors. Fear not! Here, we'll list some potential pitfalls and show you how to address them.
Location permissions are crucial when using the geolocator plugin, as the app requires access to the device's location. If the permission to access the user's location is denied or not requested, you will receive a PermissionDeniedException.
You can handle this error by requesting permission from the user again. If the permission remains denied after requesting, it might be denied permanently, and attempting to request permission again could cause annoyances. In these cases, you can provide an explanatory UI to guide the user to enable location permissions through the app settings.
1if (permission == LocationPermission.deniedForever) { 2 // Permissions are denied forever, handle appropriately. 3 return Future.error( 4 'Location permissions are permanently denied, we cannot request permissions.'); 5}
Another most common error is when the location services are disabled on the user's device. You can detect this case and notify the user accordingly.
1serviceEnabled = await Geolocator.isLocationServiceEnabled(); 2if (!serviceEnabled) { 3 // Location services are not enabled don't continue 4 // accessing the position and request users of the 5 // App to enable the location services. 6 return Future.error('Location services are disabled.'); 7}
As a best practice, always check if location services are enabled before accessing location data. It prevents unnecessary errors and enhances user experience.
Sometimes, you might face a problem while fetching location data due to several reasons including poor GPS signal, or the device is in airplane mode. You can handle these errors by using try-catch blocks while getting location data.
1try { 2 Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); 3} 4catch (e) { 5 print(e); 6}
You might encounter These common errors while working with the Flutter geolocator package. Handling them correctly is crucial to avoid app crashes and enhance user experience.
Let's dive into some if the best practices you should incorporate while using the geolocator package in your Flutter app. Remembering these will ensure you develop an app that effectively uses the device's location data and provides an enhanced user experience.
Always check the status of location permissions before calling any location-related method. If the permission is denied, provide an explanatory UI guiding the user to allow the permission through the app settings. If the permission is denied forever, consider providing alternatives as these users can't benefit from the location-based features of your application.
Monitoring the status of device location services is equally important. Prompt the user to turn on the location services if they are turned off. Also, remind the user to enable high-precision location settings for more accurate location data.
Knowing the exact requirements of your app will allow you to load location data more efficiently. If high-precision location data isn't necessary, using lower accuracy can save battery life on the user's device.
There’s always a chance that something unexpected might occur — some errors are out of your control. Issues may come up such as poor GPS signal, no internet connectivity or the device being in airplane mode. You can use try-catch blocks while invoking methods that interact with location data.
Repeated location requests can drain battery life and may lead to a poor user experience. Avoid requesting location updates when they are not needed. For instance, if your app needs to display the user's current location on a map, you don't need continuous location updates. In such cases, requesting a location when the user opens the app or the specific feature is better.
Remember that user location is sensitive data. Be transparent about how it's being used and stored. Never use or share location data without the user's knowledge and consent.
Following these best practices can help you create an efficient, effective, and user-friendly geolocation app with the Flutter geolocator package.
Throughout this guide, we delved into the ins and outs of the Flutter geolocator and how to harness its full potential. The geolocator plugin simplifies location-based features, granting you direct and easy access to platform-specific location services and improving your Flutter app's functionality and user experience.
We explored various aspects of geolocator, including obtaining the user's current location, listening to location updates, checking location services and permissions, and calculating distances between geographical points.
The ability to seamlessly integrate geolocation functionality into our apps opens up an endless array of possibilities. The geolocator plugin is helpful for map-based applications. It can be used to create user location-triggered actions, location-based notifications, or any feature where understanding the user's geographical position is beneficial.
Embracing the capabilities of geolocation in Flutter applications can take your projects to a whole new level. As stated earlier, location is a crucial feature for many mobile apps, and knowing how to include and manage it can make your apps stand out in this highly competitive marketplace. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.