geo locator get latitude longitude to full address
geo locator get latitude longitude to full address

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial Article, Will learn how to get current location coordinates (latitude & Longitude) in flutter & also get location address name from lat & long coordinates.

When you are working on service based app such as E-Commerce, Delivery then you need get user’s current location to provide your services to user location.
Therefore, you need to implement GeoLocation in your flutter project, so you are here looking for best tutorial for implementing GeoLocation into your flutter app.

Today, In this flutter Article, We’ll go through implementing geolocation to get latitude & longitude of a device current location & also get full address details based on current location lat & long in flutter.

Video Tutorial on Flutter GeoLocation – Example

Package used to get current location in flutter

To get current location in flutter we will make use of 2 flutter package.

  • GeoLocator: To get user’s device present location Latitude & Longitude in flutter.
  • GeoCoding: To get location address using lat & long coordinates (placemarkfromcoordinates) (lat long to address)

So let’s begin, without wasting more time.

Start by creating new flutter project or by opening existing project where you want to implement Locations Services.

1. Adding location package in flutter pubspec.yaml file

Open pubspec.yaml file in your flutter project & under dependencies section add this 2 packages (geolocator & geocoding).

dependencies:
  geolocator: #latest version
  geocoding:  #latest version

then hit pub get button or run command flutter put get


2. Location access permission in Android & iOS

Android

android > app > src > main > AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

iOS

ios > Runner > Info.plist

    <key>NSLocationAlwaysUsageDescription</key>
    <string>Needed to access location</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Needed to access location</string>

3. Flutter method to get current user latitude & longitude location

The below method will return location position from which we can extract lat & long coordinates points.

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

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      await Geolocator.openLocationSettings();
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
      
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }

And the above method can also handle turning on geolocation in device (if off) & also ask permission from user to ACCESS_FINE_LOCATION.


4. Method to get full address from latitude & longitude co-ordinates (lat long to address)

The below method will receive parameter i.e. location position by using which we can convert lat long to address.

Future<void> GetAddressFromLatLong(Position position)async {
    List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
    print(placemarks);
    Placemark place = placemarks[0];
    Address = '${place.street}, ${place.subLocality}, ${place.locality}, ${place.postalCode}, ${place.country}';
    
  }


Complete Code – Flutter get latitude & longitude then convert lat long to address

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: Homepage(),
    );
  }
}

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

  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {

  String location ='Null, Press Button';
  String Address = 'search';

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

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      await Geolocator.openLocationSettings();
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }

  Future<void> GetAddressFromLatLong(Position position)async {
    List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
    print(placemarks);
    Placemark place = placemarks[0];
    Address = '${place.street}, ${place.subLocality}, ${place.locality}, ${place.postalCode}, ${place.country}';
    setState(()  {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Coordinates Points',style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
            SizedBox(height: 10,),
            Text(location,style: TextStyle(color: Colors.black,fontSize: 16),),
            SizedBox(height: 10,),
            Text('ADDRESS',style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
            SizedBox(height: 10,),
            Text('${Address}'),
            ElevatedButton(onPressed: () async{
              Position position = await _getGeoLocationPosition();
              location ='Lat: ${position.latitude} , Long: ${position.longitude}';
              GetAddressFromLatLong(position);
            }, child: Text('Get Location'))
          ],
        ),
      ),
    );
  }
}

Output