Hello guys, Today we are going to learn how to fetch current location address from Google Maps
Here we are using google_maps_plugin to show Google Maps.
If you don't know how to Load Maps, please check my previous post Show Markers on Maps.
Check Show Multiple Markers on Google Maps
Add dependencies:
dev_dependencies:
flutter_test:
sdk: flutter
permission_handler:
google_maps_flutter:
geolocator:
geocoder:
|
For Android update Manifest file with Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
So Let's create Statefull widget with Google Maps.
class MyMap extends StatefulWidget{ } @override CameraUpdate.newCameraPosition(_cameraPosition)); markers:_markers , ], )); |
If we run the app, it will show the Map with location at LatLng(0, 0).
Now we need to move the camera to our current position so lets add below code
Future getCurrentLocation() async {
LocationPermission permission = await Geolocator.checkPermission();
if (permission != PermissionStatus.granted) {
LocationPermission permission = await Geolocator.requestPermission();
if (permission != PermissionStatus.granted)
getLocation();
return;
}
getLocation();
}
List<Address> results = [];
getLocation() async
{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.latitude);
setState(() {
latlong=new LatLng(position.latitude, position.longitude);
_cameraPosition=CameraPosition(target:latlong,zoom: 10.0 );
if(_controller!=null)
_controller.animateCamera(
CameraUpdate.newCameraPosition(_cameraPosition));
_markers.add(Marker(markerId: MarkerId("a"),draggable:true,position: latlong,icon:
BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueBlue),onDragEnd: (_currentlatLng){
latlong = _currentlatLng;
}));
});
}
|
So here we are using the Geolocator to fetch the current location from device
For this we need to add the geolocator: ^5.1.5 in pubspec.yaml
Display Current address on TextFiled
So now we need to show the current address on the Text filed for this we need to add one text filed in our UI
Positioned( |
We have to use geocoder package to fetch address from LatLang values
update getCurrentAddress function with below code
getCurrentAddress() async
{
final coordinates = new Coordinates(latlong.latitude, latlong.longitude);
results = await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = results.first;
if(first!=null) {
var address;
address = first.featureName;
address = " $address, ${first.subLocality}" ;
address = " $address, ${first.subLocality}" ;
address = " $address, ${first.locality}" ;
address = " $address, ${first.countryName}" ;
address = " $address, ${first.postalCode}" ;
print("address ${first.toString()}");
print(address);
locationController.text = address;
}
}
|
Now it will show the Current Address in the Text filed.
Lets check final code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:permission_handler/permission_handler.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geocoder/geocoder.dart';
void main() {
runApp(MaterialApp(home: MyHomePage()));
}
class MyHomePage extends StatefulWidget{
@override
State createState() {
// TODO: implement createState
return MyHomePageState();
}
}
class MyHomePageState extends State{
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: MyMap(),
);
}
}
class MyMap extends StatefulWidget{
@override
State createState() {
// TODO: implement createState
return MyMapState();
}
}
class MyMapState extends State{
LatLng latlong=null;
CameraPosition _cameraPosition;
GoogleMapController _controller ;
Set<Marker> _markers={};
TextEditingController locationController = TextEditingController();
@override
void initState() {
// TODO: implement initState
super.initState();
_cameraPosition=CameraPosition(target: LatLng(0, 0),zoom: 10.0);
getCurrentLocation();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return SafeArea(child: Stack(
children: [
(latlong!=null) ?GoogleMap(
initialCameraPosition: _cameraPosition,
onMapCreated: (GoogleMapController controller){
_controller=(controller);
_controller.animateCamera(
CameraUpdate.newCameraPosition(_cameraPosition));
},
markers:_markers ,
):Container(),
Positioned(
top: 50.0,
right: 15.0,
left: 15.0,
child: Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3.0),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(1.0, 5.0),
blurRadius: 10,
spreadRadius: 3)
],
),
child: TextField(
cursorColor: Colors.black,
controller: locationController,
decoration: InputDecoration(
icon: Container(
margin: EdgeInsets.only(left: 20, top: 0),
width: 10,
height: 10,
child: Icon(
Icons.location_on,
color: Colors.green,
),
),
hintText: "pick up",
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15.0, top: 12.0),
),
),
),
),
],
));
}
Future getCurrentLocation() async {
LocationPermission permission = await Geolocator.checkPermission();
if (permission != PermissionStatus.granted) {
LocationPermission permission = await Geolocator.requestPermission();
if (permission != PermissionStatus.granted)
getLocation();
return;
}
getLocation();
}
List<Address> results = [];
getLocation() async
{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.latitude);
setState(() {
latlong=new LatLng(position.latitude, position.longitude);
_cameraPosition=CameraPosition(target:latlong,zoom: 10.0 );
if(_controller!=null)
_controller.animateCamera(
CameraUpdate.newCameraPosition(_cameraPosition));
_markers.add(Marker(markerId: MarkerId("a"),draggable:true,position: latlong,icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueBlue),onDragEnd: (_currentlatLng){
latlong = _currentlatLng;
}));
});
getCurrentAddress();
}
getCurrentAddress() async
{
final coordinates = new Coordinates(latlong.latitude, latlong.longitude);
results = await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = results.first;
if(first!=null) {
var address;
address = first.featureName;
address = " $address, ${first.subLocality}" ;
address = " $address, ${first.subLocality}" ;
address = " $address, ${first.locality}" ;
address = " $address, ${first.countryName}" ;
address = " $address, ${first.postalCode}" ;
locationController.text = address;
}
}
}
|
In my Next Post I will show you How to drag the Marker to different location on Map and fetch the current Address.
Check Show Multiple Markers on Google Maps
Check Image Picker in Flutter
Article Contributed By :
|
|
|
|
19656 Views |