How to Get Current Location in Flutter — Geolocator

How to Get Current Location in Flutter — Geolocator

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.


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: ^{laest_version}
  geocoding: ^{laest_version}        

Or run the following command:

$ flutter pub add geolocator
$ flutter pub add geocoding        

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 to 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

We must have the user’s permission to get the user's location. 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:

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:maps/functions.dart';

class LocationPage extends StatefulWidget {
  const LocationPage({super.key});

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

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

  @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: () async {},
                child: const Text("Get Current Location"),
              )
            ],
          ),
        ),
      ),
    );
  }
}
        


3. Get the User’s Latitude and Longitude

Next, we create a LocationHandler (abstract class) for all methods we need.

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

abstract class LocationHandler {
  static Future<bool> handleLocationPermission() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 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) {
        // Location permissions are denied
        return false;
      }
    }
    if (permission == LocationPermission.deniedForever) {
      // Location permissions are permanently denied, we cannot request permissions.

      return false;
    }
    return true;
  }

  static Future<Position?> getCurrentPosition() async {
    try {
      final hasPermission = await handleLocationPermission();
      if (!hasPermission) return null;
      return await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
      );
    } catch (e) {
      return null;
    }
  }

  static Future<String?> getAddressFromLatLng(Position position) async {
    try {
      List<Placemark> placeMarks =
          await placemarkFromCoordinates(position.latitude, position.longitude);
      Placemark place = placeMarks[0];
      return "${place.street}, ${place.subLocality},${place.subAdministrativeArea}, ${place.postalCode}";
    } catch (e) {
      return null;
    }
  }
}
        

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


Then call methods in 'onPressed' :

              ElevatedButton(
                onPressed: () async {
                  _currentPosition = await LocationHandler.getCurrentPosition();
                  _currentAddress = await LocationHandler.getAddressFromLatLng(
                      _currentPosition!);
                  setState(() {});
                },
                child: const Text("Get Current Location"),
              ),        


The final result will look like this:



And that’s it! You’re now equipped to fetch the user’s current location address in your Flutter app. Feel free to explore additional features and customize the user experience. Happy coding! ??

要查看或添加评论,请登录

Mina Zarif的更多文章

社区洞察

其他会员也浏览了