How to Get User’s Current Location Address in Flutter — Geolocator & Geocoding

Fernando Putra
6 min readApr 15, 2022

--

In today’s mobile applications, location-based services are among the most essential and powerful features. Suppose you look at the most popular apps. In that case, they all use the user’s location services to do things like recommending nearby places, localizing mobile advertising, contextualizing learning and research, etc.

Geolocation and reverse geocoding are the two processes for determining a user’s physical location.

Geolocation is the process of determining or estimating geographic coordinates. Whereas reverse geocoding is the process of converting geographic coordinates into a human-readable address.

Fortunately, there are flutter packages that can accomplish these processes: Geolocator and geocoding packages. These packages provide easy access to platform-specific location services and geocoding/reverse-geocoding features.

In this article, we’ll learn how to get the user’s current location address with geolocator and geocoding packages and show it on the screen.

1. Setting up The Project

To begin, we must add the required dependencies, the geolocator and geocoding packages to your pubspec.yaml file.

dependencies:
geolocator: ^8.2.0
geocoding: ^2.0.4

Or run the following command:

$ flutter pub add geolocator
$ flutter pub add geocoding
// This will add the same line to your package's pubspec.yaml

Next, we need to add permission configuration for Android and iOS.

For Android

  • First, we need to add the following lines below to your gradle.properties file:
android.useAndroidX=true
android.enableJetifier=true
  • Next, make sure to set the compileSdkVersion in your android/app/build.gradle file to 31:
android {
compileSdkVersion 31

// ...
}
  • Then, we need to add either the ACCESS_FINE_LOCATION or the ACCESS_COARSE_LOCATION permission your android/app/src/main/AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

ACCESS_FINE_LOCATION is the most precise, whereas ACCESS_COARSE_LOCATION gives results equal to about a city block.

For iOS

  • We need to add the following lines inside ios/Runner/Info.plist to access the device’s location
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>

Lastly, replace the content of your main.dart file with the following code, and we’re all set.

2. Handle Location Services and Permissions

To get the user’s location, we must have the user’s permission. So, we’ll create a method to check and request the location services and permission. First, create a new StatefulWidget class file called location_page.dart in the lib folder of your project, and add the following code for the UI:

class LocationPage extends StatefulWidget {
// ...
}

class _LocationPageState extends State<LocationPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Location Page")),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('LAT: '),
const Text('LNG: '),
const Text('ADDRESS: '),
const SizedBox(height: 32),
ElevatedButton(
onPressed: () {},
child: const Text("Get Current Location"),
)
],
),
),
),
);
}
}

This will create Text widget to show the latitude, longitude, address, and a button to get the user’s current location.

Next, create a method to check and request the user’s permission.

Future<bool> _handleLocationPermission() async {
bool serviceEnabled;
LocationPermission permission;

serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Location services are disabled. Please enable the services')));
return false;
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Location permissions are denied')));
return false;
}
}
if (permission == LocationPermission.deniedForever) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Location permissions are permanently denied, we cannot request permissions.')));
return false;
}
return true;
}

In this method, we first check whether the location service is enabled or disabled; if it’s disabled, we show the snackbar and return false. Then, we call the checkPermission() method to check if the user already granted permission to acquire the device’s location.

If the permission is denied, we call the requestPermission() method to request permission to access the device’s location. If the permission is permanently denied, we show the snackbar and return false. Otherwise, we return true, meaning that permissions are granted.

3. Get the User’s Latitude and Longitude

It’s time to add the geolocation functionality. To query the current location of the device, make a call to the getCurrentPosition() method. For example:

import 'package:geolocator/geolocator.dart';
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

First, we create variables for storing the current address and position.

class _LocationPageState extends State<LocationPage> {
String? _currentAddress;
Position? _currentPosition;

Next, we create _getCurrentLocation() method, which calls the _handleLocationPermission() method to check whether the permission is granted or not. If yes, we create an instance of geolocator and make a call to the getCurrentPosition() method and get the current location as a Position.

Future<void> _getCurrentPosition() async {
final hasPermission = await _handleLocationPermission();
if (!hasPermission) return;
await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high)
.then((Position position) {
setState(() => _currentPosition = position);
}).catchError((e) {
debugPrint(e);
});
}

After that, replace the Column widget with the following code to display the latitude and longitude obtained from the _currentPosition variable.

child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('LAT: ${_currentPosition?.latitude ?? ""}'),
Text('LNG: ${_currentPosition?.longitude ?? ""}'),
Text('ADDRESS: ${_currentAddress ?? ""}'),
const SizedBox(height: 32),
ElevatedButton(
onPressed: _getCurrentPosition,
child: const Text("Get Current Location"),
)
],
),

The preview will look like this:

When you press the Get Current Location button, you will initially see a location access request to your app. Once you allow, the latitude and longitude of your current location will appear on the screen.

4. Convert Latitude and Longitude to a Human-Readable Address

The last step is translating the latitude and longitude coordinates into an address. This can be achieved by making a call to the placemarkFromCoordinates() method of the geocoding package. For example:

import 'package:geocoding/geocoding.dart';
List<Placemark> placemarks = await placemarkFromCoordinates(52.2165157, 6.9437819);

Create a _getAddressFromLatLng() method that passes a Position as a parameter, call the placemarkFromCoordinates() method, and set the _currentAddress with the Placemark information, such as street, locality, postalCode, country, and more.

Future<void> _getAddressFromLatLng(Position position) async {
await placemarkFromCoordinates(
_currentPosition!.latitude, _currentPosition!.longitude)
.then((List<Placemark> placemarks) {
Placemark place = placemarks[0];
setState(() {
_currentAddress =
'${place.street}, ${place.subLocality},
${place.subAdministrativeArea}, ${place.postalCode}';
});
}).catchError((e) {
debugPrint(e);
});
}
}

Then, we need to call the _getAddressFromLatLng() method inside the _getCurrentLocation() method.

Future<void> _getCurrentPosition() async {
// ...

await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high)
.then((Position position) {
setState(() => _currentPosition = position);
_getAddressFromLatLng(_currentPosition!);
}).catchError((e) {
debugPrint(e);
});
}

After all, this is how the location_page.dart looks.

The final result will look like this:

Congrats, you have learned how to get the user’s current location in your Flutter project. This is just a little introduction to the geolocator and geocoding packages. But I hope this article helped you to get started with these packages in Flutter 😁.

You can access the repository of this article here on GitHub.

Thank you for reading! If you found this article helpful, kindly share it with your friends and follow my profile for future updates. Your support is much appreciated! PS: It would mean even more if you donate a pizza 🍕 here. ✌️

--

--