Android Get Location with Google API Service – Tutorial

 

Google Play Services

The Android Get Location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking, geofencing, and activity recognition.

Google API Client

GoogleApiClient is used with a variety of static methods. Some of these methods require that GoogleApiClient be connected, some will queue up calls before GoogleApiClient is connected; check the specific API documentation to determine whether you need to be connected.Before any operation is executed, the GoogleApiClient must be connected.

A newer api called FusedLocationApi was introduced which connects with GoogleApiClient and gives us the best location available.

What is GPS

GPS or Global Positioning System is a network of orbiting satellites that send precise details of their position in space back to earth. The signals are obtained by GPS receivers, such as navigation devices and are used to calculate the exact position, speed and time at the vehicles location.

In my previous tutorial i explained about Android GPS, Location Manager and Google Map, I explained how to get device location (latitude & longitude) and show it on Google Map.

As this app needs updated Google Play Services, we need to setup the play services first. If you have the play services installed already, update them to latest version using Android SDK Manager.

Step by Step Tutorial

Step 1: Open Android Studio.

Step 2: Create a new project as follows:

  • If you see the Welcome to Android Studio dialog, choose Start a new Android Studio project, available under ‘Quick Start’ on the right of the dialog.
  • Otherwise, click File in the Android Studio menu bar, then New, New Project.

Step 3: Enter your app name, company domain, and project location, as prompted. Then click Next.

Step 4: Select the form factors you need for your app. If you’re not sure what you need, just select Phone and Tablet. Then click Next.

Step 5: Select Google Maps Activity in the ‘Add an activity to Mobile’ dialog. Then click Next.

Step 6: Enter the activity name, layout name and title as prompted. The default values are fine. Then click Finish.

After that wait for few seconds. Android Studio starts Gradle and builds of your project.

Get a Google API Key

Step 7: Copy the link provided in the google_maps_api.xml file and paste it into your browser. The link takes you to the Google API Console and supplies the required information to the Google API Console via URL parameters, thus reducing the manual input required from you.

Step 8: Follow the instructions to create a new project on the Google API Console or select an existing project.

Google Console API

Step 9: Copy the resulting API key.

Google Console API Key

Step 10:  Go back to Android Studio, and paste the API key into the <string> element in the google_maps_api.xml file.

API Key

Step 11: Now debug your app (press shift+F10) in emulator or any attached device and see the output of build app. you will see the screen like below image.

Step 12: Goto the MapActivity.java file and import following packages.

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;

Step 13: Implement ConnectionCallbacks, OnConnectionFailedListener, LocationListener  on public class MapActivity.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

Step 14: Declare object or variable of GooglApiClient, Location, LocationRequest.

private GoogleApiClient mGoogleApiClient;
private  Location mLocation;
double lat, lng;
private LocationRequest mLocationRequest;

Step 15: Make a builder for GoogleApiClient in onCreate() method.

if(mGoogleApiClient==null) {
    mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

Step 16: Add following methods in MapActivity.java file. they are must be declare if we are using ConnectionCallbacks, OnConnectionFailedListener, LocationListener.

// must declare methods //
public void onStart(){
 
}
public void onStop(){
  
}
public void onPause(){
    
}
public void onResume(){
  
}

protected void startLocationUpdates(){
   
}

protected  void stopLocationUpdate(){
    
}

public void onLocationChanged(Location location){

}

public void onConnectionSuspended(int arg0){

}
public void onStatusChange(String provider, int status, Bundle extras){

}

public void onConnected(Bundle args0){

  
}
public void onConnectionFailed(ConnectionResult result){

}

Step 17: Create a method for request location update.

protected  void createLocationRequest(){

    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED
            ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(20000); // 20 seconds
        mLocationRequest.setFastestInterval(10000); //10 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    }

}

Step 18: Create methods to start and stop location updates.

// create method for location update //
protected void startLocationUpdates(){
    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED
            ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) {

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

protected  void stopLocationUpdate(){
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}

Full Source Code

MapsActivity.java

import android.*;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;

import java.security.Permission;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

 private GoogleMap mMap;
 SupportMapFragment mapFragment;
 private GoogleApiClient mGoogleApiClient;
 private Location mLocation;
 double lat, lng;
 private LocationRequest mLocationRequest;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_maps);
 // Obtain the SupportMapFragment and get notified when the map is ready to be used.
 mapFragment = (SupportMapFragment) getSupportFragmentManager()
 .findFragmentById(R.id.map);

 createLocationRequest();
 // make a buidler for GoogleApiClient //
 if(mGoogleApiClient==null) {
 mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
 .addConnectionCallbacks(this)
 .addOnConnectionFailedListener(this)
 .addApi(LocationServices.API)
 .build();
 }
 }

 protected void createLocationRequest(){

 if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED
 ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) {

 mLocationRequest = new LocationRequest();
 mLocationRequest.setInterval(20000); // 20 seconds
 mLocationRequest.setFastestInterval(10000); //10 seconds
 mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
 }
 }
 
 @Override
 public void onMapReady(GoogleMap googleMap) {
 mMap = googleMap;

 // Add a marker in Sydney and move the camera
 LatLng sydney = new LatLng(lat, lng);
 mMap.addMarker(new MarkerOptions().position(sydney).title("i'm Here..."));
 mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
 }

 // must declare methods //

 public void onStart(){
 mGoogleApiClient.connect();
 super.onStart();
 if(mGoogleApiClient.isConnected()){
 startLocationUpdates();
 }
 }
 public void onStop(){
 mGoogleApiClient.disconnect();
 stopLocationUpdate();
 super.onStop();
 }
 public void onPause(){
 mGoogleApiClient.disconnect();
 stopLocationUpdate();
 super.onPause();

 }
 public void onResume(){
 mGoogleApiClient.connect();
 super.onResume();
 if(mGoogleApiClient.isConnected()){
 startLocationUpdates();
 }
 }

 // create method for location update //
 protected void startLocationUpdates(){
 if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED
 ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) {

 LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
 }
 }

 protected void stopLocationUpdate(){
 LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
 }

 // Must Declare LocatonListener Methods //
 public void onLocationChanged(Location location){
 if(location!=null){
 lat = location.getLatitude();
 lng = location.getLongitude();
 mapFragment.getMapAsync(this);
 }
 }

 public void onConnectionSuspended(int arg0){

 }
 public void onStatusChange(String provider, int status, Bundle extras){

 }

 // Must Declare Callback Methods //
 public void onConnected(Bundle args0){

 if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED
 ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) {
 mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
 if(mLocation!=null){
 lat=mLocation.getLatitude();
 lng = mLocation.getLatitude();
 mapFragment.getMapAsync(this);
 }
 if(mGoogleApiClient.isConnected()){
 startLocationUpdates();
 }
 }
 }
 public void onConnectionFailed(ConnectionResult result){
 }
}

AndroidManifest.xml

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

    <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">

      
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

google_maps_api.xml

<resources>

    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
        AIzaSyC5X4Sd4zemUKUwoquH_bSbDx05D-DAfcM

    </string>
</resources>

activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.suraj.userlocationwithgoogleapiservice.MapsActivity" />

                    

    3 thoughts on “Android Get Location with Google API Service – Tutorial

    Suraj Parkash
    17/03/2017
    Reply

    very useful content

    wan
    03/06/2017
    Reply

    i manage to get the current location but once i click “back” button its stopped working.can u help me?

Post a comment

Your email address will not be published. Required fields are marked *