Android Location using Google Play Services

Google introduced FusedLocationApi in google Play Services to get location and location updates, Google play services provide location updates much efficiently.

FusedLocationApi connects with GoogleApiClient to provide location and location updates.

So, Let’s Start.

In this tutorial, I will show you how to get Location from google play services in your application.

For Eclipse ADT users add download google play services library by following steps:-

1.Copy the library project at <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ to the location where your project.

2.Import the library project into your project by File->Import, select Android, Existing android code into your workspace and browse to the copy of project and then click Finish.

For Android Studio users add  dependency in your Gradle file

compile ‘com.google.android.gms:play-services:8.4.0’

To use Google Play Services  in our application we need GoogleMapsApi_Key

you can get this key from google developers console  from here.

we use this API key in AndroidManifest.xml file

Carefully add following permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

So, now we are ready to create New Project to get Location.

1.Open Eclipse or Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2. Now Create layout file for MainActivity.java that will be our mainscreen

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/getlocation"
        android:text="GetLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/getlocationupdates"
        android:text="getLocationUpdates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/log"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3. Now we need to implement three Listeners ConnectionCallbacks, OnConnectionFailedListener and Location Listener to connect googleapiclient and get location as well as Location updates in MainActivity.java

4.in this we will first check the availability of Google Play Services by calling checkGooglePlayServices().

5.If googlePlayServices are available, then we will build googleApiClient by calling setUpGoogleClient() and call createLocationRequest() to get Location updates.

6. Once googleApiClient is connected then we will call displayMyLocation() to display current Location.

7. createLocationRequest() is used to get Location Updates by setting location updating distance and location updating time.

8. getPeriodicLocationUpdates() will display Location Updations.

MainActivity.java

package com.coderzpassion.gplaceslocation;

import android.app.Activity;
import android.content.ComponentCallbacks;
import android.location.Location;
import android.location.LocationListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private Location mylocation;
    // google client for connecting to Google Api
    private GoogleApiClient googleApiClient;
    // flag to get location updates
    private boolean getLocationUpdates=false;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    //for location request
    private LocationRequest locationRequest;
    // for location updates
    private int locationupdate = 8000; //in milliseconds
    private int locationdistance = 10; // in meters

    //button to get my current location, getlocation updates
    Button getmylocation,getlocationupdates;
    // textviews to show latitude and longitude
    TextView lat, log;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getmylocation = (Button) findViewById(R.id.getlocation);
        lat = (TextView) findViewById(R.id.lat);
        log = (TextView) findViewById(R.id.log);
        getlocationupdates=(Button)findViewById(R.id.getlocationupdates);
        getlocationupdates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
           getPeriodicLocationUpdates();

            }
        });
        //check if google play services available
        if (checkGooglePlayServices()) {
            // set up google client
            setUpGoogleClient();

            //set Location Request
            createLocationRequest();
        }

        getmylocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayMyLocation();
            }
        });

    }

    public boolean checkGooglePlayServices() {
        GoogleApiAvailability gApi = GoogleApiAvailability.getInstance();
        int resultCode = gApi.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (gApi.isUserResolvableError(resultCode)) {
                gApi.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(this, "Google Play Services not Avaliable", Toast.LENGTH_LONG).show();
                finish();
            }
            return false;
        }
        return true;
    }

    public void setUpGoogleClient() {
        // Create an instance of GoogleAPIClient.
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    public void displayMyLocation() {
        mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (locationRequest != null) {
            lat.setText("latitude" + String.valueOf(mylocation.getLatitude()));
            log.setText("longitude" + String.valueOf(mylocation.getLongitude()));
        }

    }

    @Override
    public void onConnected(Bundle bundle) {
        displayMyLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        googleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    protected void onStart() {
        super.onStart();
        if (googleApiClient != null) {
            googleApiClient.connect();
        }

    }

    protected void onStop() {
        if (googleApiClient != null) {
            googleApiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void createLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setInterval(locationupdate); //in milliseconds
        locationRequest.setFastestInterval(5000); //in milliseconds
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setSmallestDisplacement(locationdistance);
    }

    protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest,this);
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }

    @Override
    public void onLocationChanged(Location location) {
         mylocation=location;
        displayMyLocation();
    }

    // get periodic updates
    private void getPeriodicLocationUpdates() {
        if (!getLocationUpdates) {
            // Changing the button text
            getlocationupdates.setText("Stop Location Updates");

            getLocationUpdates = true;

            // Starting the location updates
            startLocationUpdates();

            Log.d("MainActivity", "Periodic location updates started!");

        } else {
            // Changing the button text to start location updtes
            getlocationupdates.setText("Start Location Updates");

            getLocationUpdates = false;

            // stop the location updates
            stopLocationUpdates();

            Log.d("MainActivity", "Periodic location updates stopped!");
        }
    }

}

Output

Screenshot_2016-02-28-13-54-42

Android Google Map v2 Tutorial With Markers

In this tutorial, I will show you how to implement GoogleMap in your application.

To use Google Maps in your application we need GoogleMapsApi_Key

you can get this key from Google developers console  from here.

we use this API key in AndroidManifest.xml file

Carefully add all permissions in AndroidManifest.xml

For Eclipse ADT users add download google play services library by following steps:-

1.Copy the library project at <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ to the location where your project.

2.Import the library project into your project by File->Import, select Android, Existing android code into your workspace and browse to the copy of the project and then click Finish.

For Android Studio users add  dependency in your Gradle file

compile ‘com.google.android.gms:play-services:8.4.0’

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.mymap" >

    <permission
        android:name="com.androidruler.mymap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.androidruler.mymap.permission.MAPS_RECEIVE" />
    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- API key for the Android Maps API v2. The value is defined as a string resource. -->
        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyB46A0jQLS9lm1x-fO07tD-EPHzoxCvMkg"/>
    </application>

</manifest>

//layout for MainActivity.java

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"      android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/mmymap"
        android:layout_alignParentTop="true"
        android:name="com.google.android.gms.maps.SupportMapFragment" />
<Button
    android:id="@+id/getlocation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="getLocation"
    android:layout_below="@+id/mmymap"
    />

    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/getlocation"/>
    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/location"/>

</RelativeLayout>

MainActivity.java

package com.androidruler.mymap;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.List;
import java.util.Locale;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {




    TextView addre,location;
    Button getLocation;
    LocationTracker tracker;
    String getadd;
    double latitude=0.0d,longitude=0.0d;
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mmymap);
        mapFragment.getMapAsync(this);
        addre=(TextView)findViewById(R.id.address);
        location=(TextView)findViewById(R.id.location);
        getLocation=(Button)findViewById(R.id.getlocation);
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //create LocationTracker Object
                tracker = new LocationTracker(MainActivity.this);

                // check if location is available
                if (tracker.isLocationEnabled) {
                    latitude = tracker.getLatitude();
                    longitude = tracker.getLongitude();

                    location.setText("Your Location is Latitude= " + latitude + " Longitude= " + longitude);
                    getadd = getCompleteAddressString(latitude, longitude);
                    addre.setText(getadd);
                    drawMarker(latitude, longitude);
                } else {
                    // show dialog box to user to enable location
                    tracker.askToOnLocation();
                }
            }
        });


    }

    @Override
    public void onMapReady(GoogleMap Map) {
        mMap=Map;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setAllGesturesEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);

    }

    public void drawMarker(double lat,double lon)
    {
        if (mMap != null) {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");

            marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

// Moving Camera to a Location with animation
            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();

            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            mMap.addMarker(marker);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder
                    .getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                android.location.Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress
                            .append(returnedAddress.getAddressLine(i)).append(
                            "\n");
                }
                strAdd = strReturnedAddress.toString();
                Log.w(" location address", ""+ strReturnedAddress.toString());
            } else {
                Log.w(" location address", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w(" location address", "Cannot get Address!");
        }
        return strAdd;
    }
}

 

LocationTracker.java

package com.androidruler.mymap;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by androidruler on 24/02/16.
 */
public class LocationTracker extends Service implements LocationListener {

     //declaring Context variable
    private final Context con;

    //flag for gps
    boolean isGPSOn=false;

    //flag for network location
    boolean isNetWorkEnabled=false;

    //flag to getlocation
    boolean isLocationEnabled=false;

    //minimum distance to request for location update
    private static final long MIN_DISTANCE_TO_REQUEST_LOCATION=1; // in meters

    // minimum time to request location updates
    private static final long MIN_TIME_FOR_UPDATES=1000*1; // 1 sec

    //location
    Location location;
    //latitude and longitude
    double latitude,longitude;

    //Declaring a LocationManager
    LocationManager locationManager;

    public LocationTracker(Context context)
    {
        this.con=context;
        checkIfLocationAvailable();
    }

    public Location checkIfLocationAvailable()
    {
        try
        {
            locationManager=(LocationManager)con.getSystemService(LOCATION_SERVICE);
            //check for gps availability
            isGPSOn=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            //check for network availablity
            isNetWorkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if(!isGPSOn && !isNetWorkEnabled)
            {
                isLocationEnabled=false;
                // no location provider is available show toast to user
                Toast.makeText(con,"No Location Provider is Available",Toast.LENGTH_SHORT).show();
            }
            else {
                isLocationEnabled=true;

                // if network location is available request location update
                if(isNetWorkEnabled)
                {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);
                   if(locationManager!=null)
                   {
                       location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                       if(location!=null)
                       {
                           latitude=location.getLatitude();
                           longitude=location.getLongitude();

                       }
                   }
                }

                if(isGPSOn)
                {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);

                    if(locationManager!=null)
                    {
                        location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if(location!=null)
                        {
                            latitude=location.getLatitude();
                            longitude=location.getLongitude();
                        }
                    }
                }
            }

        }catch (Exception e)
        {

        }

        return location;
    }

    // call this to stop using location
    public void stopUsingLocation()
    {
        if(locationManager!=null)
        {
            locationManager.removeUpdates(LocationTracker.this);
        }
    }
       // call this to getLatitude
    public double getLatitude()
    {
        if(location!=null)
        {
            latitude=location.getLatitude();
        }
        return latitude;
    }
    //call this to getLongitude
    public double getLongitude()
    {
        if(location!=null)
        {
            longitude=location.getLongitude();
        }
        return longitude;
    }

    public boolean isLocationEnabled() {
        return this.isLocationEnabled;
    }

    //call to open settings and ask to enable Location
    public void askToOnLocation()
    {
        AlertDialog.Builder dialog=new AlertDialog.Builder(con);

        //set title
        dialog.setTitle("Settings");
        //set Message
        dialog.setMessage("Location is not Enabled.Do you want to go to settings to enable it?");
        // on pressing this will be called
        dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                con.startActivity(intent);
            }
        });

        //on Pressing cancel
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // show Dialog box
        dialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Output

Screenshot_2016-02-27-18-12-47                     Screenshot_2016-02-27-18-12-52

Android GPS Location Manager Tutorial

if you are making any location-based application you can follow this tutorial to get Location automatically from LocationTracker.java class.

In this tutorial,  I will show you how to get current Location and get an address from latitude and longitude.In this we have

  • MainActivity as Activity to get Location on performing Click
  • LocationTracker class to get Location

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.mymap" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
    </application>

</manifest>

 

//layout for MainActivity.java

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
    android:id="@+id/getlocation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="getLocation"
    android:layout_above="@+id/location"/>

    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/location"/>

</RelativeLayout>

 

MainActivity.java

package com.androidruler.mymap;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity {


   TextView address,location;
    Button getLocation;
    LocationTracker tracker;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        address=(TextView)findViewById(R.id.address);
        location=(TextView)findViewById(R.id.location);
        getLocation=(Button)findViewById(R.id.getlocation);
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //create LocationTracker Object
                tracker=new LocationTracker(MainActivity.this);

                // check if location is available
                if(tracker.isLocationEnabled)
                {
                    double latitude=tracker.getLatitude();
                    double longitude=tracker.getLongitude();

                    location.setText("Your Location is Latitude= " + latitude + " Longitude= " + longitude);
                  String addres= getCompleteAddressString(latitude,longitude);
                  address.setText(addres);
                }
                else
                {
                    // show dialog box to user to enable location
                    tracker.askToOnLocation();
                }
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder
                    .getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                android.location.Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress
                            .append(returnedAddress.getAddressLine(i)).append(
                            "\n");
                }
                strAdd = strReturnedAddress.toString();
                Log.w(" location address", ""+ strReturnedAddress.toString());
            } else {
                Log.w(" location address", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w(" location address", "Cannot get Address!");
        }
        return strAdd;
    }
}

//location tracker to get current location updates periodically

LocationTracker.java

package com.androidruler.mymap;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by androidruler on 24/02/16.
 */
public class LocationTracker extends Service implements LocationListener {

     //declaring Context variable
    private final Context con;

    //flag for gps
    boolean isGPSOn=false;

    //flag for network location
    boolean isNetWorkEnabled=false;

    //flag to getlocation
    boolean isLocationEnabled=false;

    //minimum distance to request for location update
    private static final long MIN_DISTANCE_TO_REQUEST_LOCATION=1; // in meters

    // minimum time to request location updates
    private static final long MIN_TIME_FOR_UPDATES=1000*1; // 1 sec

    //location
    Location location;
    //latitude and longitude
    double latitude,longitude;

    //Declaring a LocationManager
    LocationManager locationManager;

    public LocationTracker(Context context)
    {
        this.con=context;
        checkIfLocationAvailable();
    }

    public Location checkIfLocationAvailable()
    {
        try
        {
            locationManager=(LocationManager)con.getSystemService(LOCATION_SERVICE);
            //check for gps availability
            isGPSOn=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            //check for network availablity
            isNetWorkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if(!isGPSOn && !isNetWorkEnabled)
            {
                isLocationEnabled=false;
                // no location provider is available show toast to user
                Toast.makeText(con,"No Location Provider is Available",Toast.LENGTH_SHORT).show();
            }
            else {
                isLocationEnabled=true;

                // if network location is available request location update
                if(isNetWorkEnabled)
                {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);
                   if(locationManager!=null)
                   {
                       location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                       if(location!=null)
                       {
                           latitude=location.getLatitude();
                           longitude=location.getLongitude();

                       }
                   }
                }

                if(isGPSOn)
                {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);

                    if(locationManager!=null)
                    {
                        location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if(location!=null)
                        {
                            latitude=location.getLatitude();
                            longitude=location.getLongitude();
                        }
                    }
                }
            }

        }catch (Exception e)
        {

        }

        return location;
    }

    // call this to stop using location
    public void stopUsingLocation()
    {
        if(locationManager!=null)
        {
            locationManager.removeUpdates(LocationTracker.this);
        }
    }
       // call this to getLatitude
    public double getLatitude()
    {
        if(location!=null)
        {
            latitude=location.getLatitude();
        }
        return latitude;
    }
    //call this to getLongitude
    public double getLongitude()
    {
        if(location!=null)
        {
            longitude=location.getLongitude();
        }
        return longitude;
    }

    public boolean isLocationEnabled() {
        return this.isLocationEnabled;
    }

    //call to open settings and ask to enable Location
    public void askToOnLocation()
    {
        AlertDialog.Builder dialog=new AlertDialog.Builder(con);

        //set title
        dialog.setTitle("Settings");
        //set Message
        dialog.setMessage("Location is not Enabled.Do you want to go to settings to enable it?");
        // on pressing this will be called
        dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                con.startActivity(intent);
            }
        });

        //on Pressing cancel
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // show Dialog box
        dialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
      this.location=location;
    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}