Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Location In Flutter

Nowadays, working with a location in the app is very common. Using the Flutter Location plugin, it’s effortless to get the user’s location on Android and iOS devices.

In this article, we’ll show how to get the user’s current location and display the address. We will also implement a demo using the location package.

location | Flutter Package
This plugin for Flutter handles getting location on Android and iOS. It also provides callbacks when location is…pub.dev


Table of Contents :

Introduction

Setup

Code Implementation

Code File

Conclusion


Introduction :

Sometimes to provide the best possible user experience, you need to know the GPS location of their device. The Location package allows you to obtain the current geographic location of the device and listen for changes. You can use this data to display maps, calculate distances, determine the direction the device is facing, and more!

Setup :

Step 1: Add the dependency

Start by adding the dependency to the pubspec.yml file

dependencies:
  location: latest version

Android: all the dependencies are automatically added to your project.

IOS:

Modify the Info.plist file to add the permission

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

It can be found inside <your-project-root-directory>/ios/Runner/ folder

Step 2: To get the user’s location import the library into MyLocation.dart

import 'package:location/location.dart';

Implement Code :

Create variables for storing address and location in the MyLocation.dart class and showing in the google map. On location change, we will display it on the screen.

LocationData _currentPosition;
String _address,_dateTime;

Now we get the location, In this function, we will get the coordinates of the user

Now we are showing coordinates on the screen.

Get address from the coordinates

Display address and coordinates

Wherever you want to display it on the screen

On Google map,

In these snippets, we are using google map and text to display the user’s coordinates and address.

Code File

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:geocoder/geocoder.dart';
import 'package:intl/intl.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';


class MyLocation extends StatefulWidget {
@override
_MyLocationState createState() => _MyLocationState();
}


class _MyLocationState extends State<MyLocation> {
LocationData _currentPosition;
String _address,_dateTime;
GoogleMapController mapController;
Marker marker;
Location location = Location();

GoogleMapController _controller;
LatLng _initialcameraposition = LatLng(0.5937, 0.9629);

@override
void initState() {
// TODO: implement initState
super.initState();
getLoc();

}

void _onMapCreated(GoogleMapController _cntlr)
{
_controller = _controller;
location.onLocationChanged.listen((l) {
_controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(l.latitude, l.longitude),zoom: 15),
),
);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(

body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/bg.jpg'), fit: BoxFit.cover),
),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: SafeArea(
child: Container(
color: Colors.blueGrey.withOpacity(.8),
child: Center(
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height/2.5,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: _initialcameraposition,
zoom: 15),
mapType: MapType.normal,
onMapCreated: _onMapCreated,
myLocationEnabled: true,
),
),
SizedBox(
height: 3,
),
if (_dateTime != null)
Text(
"Date/Time: $_dateTime",
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
),

SizedBox(
height: 3,
),
if (_currentPosition != null)
Text(
"Latitude: ${_currentPosition.latitude}, Longitude: ${_currentPosition.longitude}",
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 3,
),
if (_address != null)
Text(
"Address: $_address",
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
SizedBox(
height: 3,
),
],
),
),
),
),
),

);
}


getLoc() async{
bool _serviceEnabled;
PermissionStatus _permissionGranted;

_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}

_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}

_currentPosition = await location.getLocation();
_initialcameraposition = LatLng(_currentPosition.latitude,_currentPosition.longitude);
location.onLocationChanged.listen((LocationData currentLocation) {
print("${currentLocation.longitude} : ${currentLocation.longitude}");
setState(() {
_currentPosition = currentLocation;
_initialcameraposition = LatLng(_currentPosition.latitude,_currentPosition.longitude);

DateTime now = DateTime.now();
_dateTime = DateFormat('EEE d MMM kk:mm:ss ').format(now);
_getAddress(_currentPosition.latitude, _currentPosition.longitude)
.then((value) {
setState(() {
_address = "${value.first.addressLine}";
});
});
});
});
}


Future<List<Address>> _getAddress(double lat, double lang) async {
final coordinates = new Coordinates(lat, lang);
List<Address> add =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
return add;
}

}

Conclusion

In this article, I have explained the location package demo, which you can modify and experiment with according to your own. This little introduction was about to get the user’s current location and display it on the map.

I hope this blog will provide you with sufficient information in trying up to get the user’s current location in your flutter projects. We will show to get the user location demo program for working location in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Leave comment

Your email address will not be published. Required fields are marked with *.