How to Get User Current Location Address in Flutter — Geolocator:

Ritesh Kumar Yadav
6 min readDec 5, 2023

--

step by step follow me

  1. In today’s mobile applications, location-based services are one of the most important and powerful features. If you look at the most popular apps, they all use the user’s location services to do certain things, such as recommending nearby places, localizing mobile advertising, contextualizing learning and research, and so on.

Table of contents

  1. Setting up the project
    ⠀⠀· For Android
    ⠀⠀· For iOS
  2. Handle location services and permissions
  3. Get user’s latitude and longitude
  4. Convert latitude and longitude to a human-readable address

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 simply 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 below inside ios/Runner/Info.plist in order 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

In order to get the user’s location, we must have user’s permission. So we will 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 and if it is 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. Else, which means the permissions are granted, we return true.

3. Get user’s latitude and longitude

Now it's time to add the geolocation functionality. To query the current location of the device, simply 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, simply 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 pressed 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 to translate 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 pass 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 just 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.

import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';

class LocationPage extends StatefulWidget {
const LocationPage({Key? key}) : super(key: key);

@override
State<LocationPage> createState() => _LocationPageState();
}

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

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;
}

Future<void> _getCurrentPosition() async {
final hasPermission = await _handleLocationPermission();

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

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);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Location Page")),
body: SafeArea(
child: Center(
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 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 😁.

A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…

Thanks for reading! If you found this article helpful, kindly share it with your friends and follow me so you’ll be notified when I publish a new article.

Also, if there are any grammatical issues, please let me know in the comments so that I can improve my writing skills.

--

--

No responses yet