Share your knowledge

Tuesday, 10 January 2017

Getting Current Location Using Fused Location API

Let us develop an application to get the current location(last known location) address using Fused Location API Service from Google Play services.


Our Final Output looks like below:



Download code from here


Here we will use Google play services Location APIs (Fused Location Provider) to get the exact last known location(which is nothing but current location) of the device.

Set up Google Play Services: To develop an application using Google Play services APIs, you need to first set up your project with Google Services SDK.
If you haven't installed the Google Play services SDK yet, then follow below steps:

1. Click on SDK Manager icon as shown below




2. Click on Launch Standalone SDK Manager as shown in below figure.



3. Expand Extras and install Google Repository as shown below



4. Add Dependencies to make your app work with Google Play services APIs, and Click on Sync Now after adding dependency.



dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'

    compile 'com.google.android.gms:play-services-location:10.0.1'

}

Note: Be sure you update this version number(10.0.1) each time Google Play services is updated, while posting this blog it is 10.0.1.

You can now begin developing features with Google Play services APIs. 

Selectively compiling APIs: Before 6.5 versions of Google Play services you should compile entire package of
APIs (compile 'com.google.android.gms:play services:10.0.1')into your application. Doing so is difficult to keep the number of methods under 65,536 limit. But you can now include selective api (based on your need).

If you want to work with wearable watches then you can only include wearable related api instead of entire package.

compile 'com.google.android.gms:play-services-wearable:10.0.1'
 
Some of other Individual Google Play services APIs:

1. Google+ :  com.google.android.gms:play-services-plus:10.0.1
2. Google Account Login: com.google.android.gms:play-services-auth:10.0.1

3. Google Actions, Base Client Library:com.google.android.gms:play-services-base:10.0.1
 
4.Google Address API: com.google.android.gms:play-services-identity:10.0.1

5.Firebase App Indexing: com.google.firebase:firebase-appindexing:10.0.1

6. Google Analytics : com.google.android.gms:play-services-analytics:10.0.1

and more....

5. Specifying App Permissions:  Application that needs location services must include either Fine Location or Coarse location permission based on your need.


Note: 

1. See the differences between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.

2. Location can be determined by two ways:
  1. Using NETWORK_PROVIDER
  2. Using GPS_PROVIDER
follow this for more details.

Let's Create Android Project:


1. Create a new project in Android Studio from File => New =>New Project and fill details.


2. Open Manifest.xml and add below code



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

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

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

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

</manifest>

2. Open values => strings.xml and add the below string values.



<resources>

    <string name="app_name">CurrentLocation</string>
    <string name="latitude">Latitude:</string>
    <string name="longitude">Longitude:</string>

</resources>

3. Open values => colors.xml and add the below code



<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="black">#000000</color>
</resources>

4. add below code under activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.currentlocation.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center|start"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/latitude"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/latitude"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:gravity="center|start"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/longitude"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/longitude"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/latitude"
            android:layout_centerHorizontal="true"
            android:textSize="20dp" />

    </LinearLayout>

</LinearLayout>


5. open MainActivity.java and paste below code:



package com.currentlocation;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private TextView latitude, longitude;
    private final int LOCATION_REQUEST_CODE = 100;

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

        latitude = (TextView) findViewById(R.id.latitude);
        longitude = (TextView) findViewById(R.id.longitude);

        //checking runtime permissions

        if (Build.VERSION.SDK_INT > 22) {

            //check run time permssion
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                //PERMISSION IS NOT GRANTED
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);

                return;
            } else {
                buildGoogleApiClient();
            }

        } else {
            buildGoogleApiClient();
        }
    }

    private void buildGoogleApiClient() {

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .enableAutoManage(this, 0, this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API) //adding location Service
                    .build();

            mGoogleApiClient.connect();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient != null)
            mGoogleApiClient.disconnect();

    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

        try {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);

            if (mLastLocation != null) {
                latitude.setText(String.valueOf(mLastLocation.getLatitude()));
                longitude.setText(String.valueOf(mLastLocation.getLongitude()));
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {

            case LOCATION_REQUEST_CODE:

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    buildGoogleApiClient();

                } else {

                    if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {

                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
                    }
                }
                break;
        }
    }
}

6. If you run the project, you can see latitude and longitude as shown in the below image.



6. Follow this tutorial to get address using AsyncTask


1 comment:

  1. how to get lat lng (this tutorial) on fragment activity?, thanks

    ReplyDelete