Skip to main content

Android: Current Location Using Fused APi on Google Maps

This tutorial gives us the simple implementation of "Fused API" to fetch the current location on google map in android. Fused API is latest among all techniques to get the location. It provides you very precise results and also uses less battery of your device.

It chooses GPS or Network provider to get to your current location. And it helps your device remember about the last saved location. Let's implement the Fused API to fetch/get the current location.

Step 1: Create a new project in Android studio. and select Maps Activity.





Step 2: Give name to your project,set location and click finish.





Step 3: Now before moving forward get a API key from Google Console. Create a new project in Google console. and then click Enable API




Step 4: Click on Google Maps Android API, to enable this api. After that click on Credentials option given on the left side bar.








Then, Click "Create Credentials" to create your API key. Copy it and paste it in xml file, as shown in below image. 


Step 5: Goto Values folder and  open "google_maps_api.xml" file. Inside this file, there is string which says "YOUR_KEY_HERE". Replace this text with your API key.



Step 6: Add the below permission to Android Manifest file.

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

Step 7: Use this code given below to get the current Location on Google Map.

Map_Activity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,  
LocationListener {

    private GoogleMap mMap;
    public static double latitude;
    public static double longitude;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    LocationManager locationManager;
    LocationRequest mLocationRequest;
    LocationListener mlocationListener;

    @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.

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        buildGoogleApiClient();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng position = new LatLng(latitude, longitude );
        mMap.addMarker(new MarkerOptions().position(position).title("Your Current Location"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
    }


 protected synchronized void buildGoogleApiClient()
    {

        Log.d("Connection","OnBuildGoogle");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }


    @Override
    public void onConnected( Bundle bundle) {

       

        if (ContextCompat.checkSelfPermission(this, 
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {

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


        }

    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed( ConnectionResult connectionResult) {

    }


    @Override
    protected void onStart() {

        Log.d("Connection","OnStart");

        mGoogleApiClient.connect();
        super.onStart();

    }


    @Override
    protected void onStop() {

        Log.d("Connection","onStop");
       // Toast.makeText(this, "OnStop", Toast.LENGTH_SHORT).show();
        mGoogleApiClient.disconnect();
        super.onStop();
    }



    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        latitude= location.getLatitude();
        longitude = location.getLongitude();

     //  Toast.makeText(this, "Lat: "+latitude+", Lng: "+longitude, Toast.LENGTH_SHORT).show();
        //stop location updates
        if (mGoogleApiClient != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }
}



XML File:

<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.currentlocationusingfusedapi.MapsActivity" />


Enjoy!!

Comments

Post a Comment

Popular posts from this blog

Android: Login Screen using Fragments

In this tutorial, our focus is on making a User/Member login activity using fragments. With the help of Fragments we will use the same activity to show User login area and also Members Login area. Prerequisite for this tutorial: You should be know how to make an Activity And most importantly you should have prior Knowledge of Fragments. For practising basic Fragment implementation refer to Android Simple Fragment Example      We have used only three activities for this: MainActivity(which represents the Login Screen) Fragments for Members area Fragment for New Users

Simple Login/Register Example using SQLite database

MainActivity.java(login Screen) package com.AndroidDevelopmentGuru.database_new; import java.util.List; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity {                                 EditText user, pass;                 Button login, not_reg;                 DatabaseHandler db;                 Cursor cursor;                                 @Override                 protected void onCreate(Bundle savedInstanceState) {                                 super.onCreate(savedInstanceState);                                 setContentView(R.layout.activity_main);