Show Current Location On Maps - Flutter, Fetch Current Location Address.

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.

So Lets create Statefull widget with Google Maps.

class MyMap extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return MyMapState();
  }

}
class MyMapState extends State{
  LatLng latlong=null;
  CameraPosition _cameraPosition;
  GoogleMapController _controller ;
  Set_markers={};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _cameraPosition=CameraPosition(target: LatLng(0, 0),zoom: 10.0);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SafeArea(child: Stack(
        children: [
          GoogleMap(
            initialCameraPosition: _cameraPosition,
            onMapCreated: (GoogleMapController controller){
              _controller=(controller);
               _controller.animateCamera(

CameraUpdate.newCameraPosition(_cameraPosition));
            },

            markers:_markers ,
            onCameraIdle: (){
              setState(() {
                
              });
            },
          )

        ],

    ));
  }

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 {
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    print(position.latitude);

    List placemark = await Geolocator()
        .placemarkFromCoordinates(position.latitude, position.longitude);

    setState(() {
      latlong=new LatLng(position.latitude, position.longitude);
      _cameraPosition=CameraPosition(target:latlong,zoom: 10.0 );
      _controller.animateCamera(

CameraUpdate.newCameraPosition(_cameraPosition));

      _markers.add(Marker(markerId: MarkerId("a"),draggable:true,position: latlong,icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),

onDragEnd: (_currentlatLng){
      latlong = _currentlatLng;

      }));
    });
  }
  
  and update intState method
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _cameraPosition=CameraPosition(target: LatLng(0, 0),zoom: 10.0);
    getCurrentLocation();
  }

So here we are using the Geolocator to fetch the current location from 
  For this we need to add the geolocator: ^5.1.5 in pubspec.yaml
  
  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(
          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),
              ),
            ),
          ),
        ),

update getCurrentLocation function with below code

Future getCurrentLocation() async {
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    print(position.latitude);

    List placemark = await Geolocator()
        .placemarkFromCoordinates(position.latitude, position.longitude);

    setState(() {
      latlong=new LatLng(position.latitude, position.longitude);
      _cameraPosition=CameraPosition(target:latlong,zoom: 10.0 );
      if(_controller!=null)
      _controller.animateCamera(

CameraUpdate.newCameraPosition(_cameraPosition));
      var address;
      address=placemark[0].name;
      address=address+","+placemark[0].subLocality;
      address=address+","+placemark[0].locality;
      address=address+","+placemark[0].country;
      address=address+","+placemark[0].postalCode;
      locationController.text=address;
      _markers.add(Marker(markerId: MarkerId("a"),draggable:true,position: latlong,icon: BitmapDescriptor.defaultMarkerWithHue(

BitmapDescriptor.hueBlue),onDragEnd: (_currentlatLng){
      latlong = _currentlatLng;
     
      }));
    });
  }

Now it will show the Current Address in the Text filed.

Lets check final code

import 'dart:async';

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

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_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 {
    Position position = await Geolocator().

getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    print(position.latitude);

    List placemark = await Geolocator()
        .placemarkFromCoordinates(position.latitude, position.longitude);

    setState(() {
      latlong=new LatLng(position.latitude, position.longitude);
      _cameraPosition=CameraPosition(target:latlong,zoom: 10.0 );
      if(_controller!=null)
      _controller.animateCamera(

CameraUpdate.newCameraPosition(_cameraPosition));
      var address;
      address=placemark[0].name;
      address=address+","+placemark[0].subLocality;
      address=address+","+placemark[0].locality;
      address=address+","+placemark[0].country;
      address=address+","+placemark[0].postalCode;
      locationController.text=address;
      _markers.add(Marker(markerId: MarkerId("a"),draggable:true,position: latlong,onDragEnd: (_currentlatLng){
        latlong = _currentlatLng;

      }));
    });
  }

}

 

In my Next Post I will show you How to drag the Marker to different location on Map and fetch the current Address.

 


Subscribe For Daily Updates