Latest Google Location API in 2018.



Old version of Google Location API only works with older versions of Google Play Services, in newer versions, the FusedLocationApi object has been deprecated. So in today’s lesson, we’ll learn how to get your device’s location with the latest version of Google Play Services, and in my opinion, this is really simple, much simpler than with the older version.

First, add dependency to your gradle:
First, add dependency to you app module:

build.gradle(Module:app)
implementation 'com.google.android.gms:play-services:11.8.0'

Next, add permission to your manifest

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

Make a layout for your activity:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bodhi64.virtuozatutorials.MainActivity">

    <TextView
        android:id="@+id/lbl_location"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:textColor="#000"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_start"
        android:layout_below="@id/lbl_location"
        android:layout_marginTop="50dp"
        android:text="start getting location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_stop"
        android:layout_below="@id/btn_start"
        android:layout_marginTop="50dp"
        android:text="stop getting location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

And now add this code to your MainActivity

MainActivity.java
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 1000;
    TextView txtLocation;
    Button btnStart, btnStop;


    FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest locationRequest;
    LocationCallback locationCallback;

    @Override
    public void onRequestPermissionsResult(
       int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE:{
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {

                    }
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtLocation = (TextView) findViewById(R.id.lbl_location);
        btnStart = (Button) findViewById(R.id.btn_start);
        btnStop = (Button) findViewById(R.id.btn_stop);
        btnStop.setEnabled(false);

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this, new String[]{
                    android.Manifest.permission.ACCESS_FINE_LOCATION
            }, REQUEST_CODE);
        } else {
            buildGoogleLocationRequest();
            buildGoogleLocationCallback();

            fusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);


            btnStart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, 
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
 && ActivityCompat.checkSelfPermission(MainActivity.this, 
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                                android.Manifest.permission.ACCESS_FINE_LOCATION
                        }, REQUEST_CODE);
                        return;
                    }
                    fusedLocationProviderClient.requestLocationUpdates(locationRequest,
                            locationCallback, Looper.myLooper());

                    btnStart.setEnabled(!btnStart.isEnabled());
                    btnStop.setEnabled(!btnStop.isEnabled());
                }
            });

            btnStop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                                android.Manifest.permission.ACCESS_FINE_LOCATION
                        }, REQUEST_CODE);
                        return;
                    }
                    fusedLocationProviderClient.removeLocationUpdates(locationCallback);

                    btnStart.setEnabled(!btnStart.isEnabled());
                    btnStop.setEnabled(!btnStop.isEnabled());
                }
            });

        }


    }

    private void buildGoogleLocationCallback() {
        locationCallback= new LocationCallback(){
            @Override
            public void onLocationResult(LocationResult locationResult) {
                for(Location location:locationResult.getLocations())
                    txtLocation.setText(String.valueOf(location.getLatitude()
                    +"/"+ String.valueOf(location.getLongitude())));
            }
        };
    }

    private void buildGoogleLocationRequest() {
        locationRequest= new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(3000);
        locationRequest.setSmallestDisplacement(10);
    }
}



And that’s it. When you run it and start getting location, you will get latitude and longitude of your current location and you can use it where ever you want 😀
Cheers

Share with your friends