Sun. Jan 20th, 2019

Display current location(latitude and longitude) in google map and save it to the Firebase database in Android

Display current location(latitude and longitude) in google map and save it to the Firebase database in Android | In this tutorial, we will learn to display our current location and save data to the firebase. Firebase is the cloud service provided by Google that gives us the tools and infrastructure to build better applications quickly. It is available for various platforms like Android, Web , IOS. It provides Realtime Database, Cloud Messaging, Storage etc.  To setup, firebase database link has been provided in the further tutorial.

Project:  CurrentLocation

Apk sample: currentlocation

Sample Output:

On clicking save button, our location is saved to the Firebase database.

Creating New Project – CurrentLocation

Open your Android Studio & create a new Project, have taken AppCompactActivity for this project.We kept all the things by default and clicked finish.

Pre-Requisites

To use this Google Service and Firebase, we have to add dependencies to our build.gradle file. To know how to add firebase to your Android Studio: https://firebase.google.com/docs/android/setup

 

Now let’s get started with coding!

Creating Layout

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="current_location_to_firebase.mytrendin.com.currentlocation.MainActivity">

    <TextView
        android:id="@+id/latitude_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/longitude_label"
        android:text="Latitude : "
        android:textStyle="italic"
        android:layout_marginLeft="85dp"
        android:textSize="22dp" />

    <TextView
        android:id="@+id/latitude_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="italic"
        android:layout_alignBaseline="@+id/latitude_label"
        android:layout_toRightOf="@+id/latitude_label"
        android:textIsSelectable="true"
        android:text="Latitude Goes Here"
        android:textSize="22dp" />

    <TextView
        android:id="@+id/longitude_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="85dp"
        android:layout_marginTop="10dp"
        android:text="Longitude : "
        android:textStyle="italic"
        android:textSize="22dp" />
    <TextView
        android:id="@+id/longitude_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/longitude_label"
        android:layout_toRightOf="@+id/longitude_label"
        android:textIsSelectable="true"
        android:textStyle="italic"
        android:text="Longitude Goes Here"
        android:textSize="22dp"/>
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save Location"
        android:padding="10dp"
        android:textSize="16dp"
        android:textStyle="bold"
        android:id="@+id/save_location"
        android:layout_centerHorizontal="true"
        android:layout_margin="16dp"
        android:layout_below="@id/longitude_label"
        android:background="@color/colorPrimary"
        android:textColor="#FFFFFF"
  />
</RelativeLayout>

 All the content of the XML file is self-explanatory but in a case of any queries feel free to comment below.Here we have four text views and one button. Text Views having ids latitude_text  and longitude_text is used to show rendered location data whereas Button is used to save location to Firebase database.

 Creating MainActivity.java

package current_location_to_firebase.mytrendin.com.currentlocation;


import android.location.Location;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
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.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;


public class MainActivity extends AppCompatActivity implements
        ConnectionCallbacks, OnConnectionFailedListener {

    private static final String TAG = "CurrentLocationApp";
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private TextView mLatitudeText;
    private TextView mLongitudeText;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mLocationDatabaseReference;
    Button saveLocationToFirebase;
    String value_lat = null;
    String value_lng=null;


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

        FirebaseApp.initializeApp(this);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mLocationDatabaseReference= mFirebaseDatabase.getReference().child("my current location");
        mLatitudeText = (TextView) findViewById((R.id.latitude_text));
        mLongitudeText = (TextView) findViewById((R.id.longitude_text));
        saveLocationToFirebase=(Button)findViewById(R.id.save_location);
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    @Override
    public void onConnected(Bundle connectionHint) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {

                        value_lat= String.valueOf(mLastLocation.getLatitude());
                        value_lng =String.valueOf(mLastLocation.getLongitude());
                mLatitudeText.setText(value_lat);
                mLongitudeText.setText(value_lng);

                saveLocationToFirebase.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mLocationDatabaseReference.push().setValue("Latitude : "+value_lat +"  & Longitude : "+value_lng);
                        Toast.makeText(MainActivity.this ,"Location saved to the Firebasedatabase",Toast.LENGTH_LONG).show();
                    }
                });
            }
    }
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }
     @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Related: 

Periodically send GPS location to Firebase with custom time frame in Android

Draw route and calculate distance between two locations in Google Maps Android

Draw route between two locations with Google Maps, using Kotlin, Android

Draw route between two locations, Google Maps in Android

Handle Multiple Geofencing in Common Areas in google map in android application

buildGoogleApiClient(): It creates an instance of Google API Client using its builder and it adds that we want to use the Location Service API by saying addApi method. We want connection callback method on the Google API client to come back to this class and OnConnectionFail also to this class and then we build it.

onConnected(): It provides a simple way of getting a location. It gets us a most recent currently available location.

You can get red line in above code when you call ApiClient in getLocation, it only shows that this call requires permission which can be rejected by the user. So, here we can add some explicit permission check to see if permission is available. If there is any kind of security exception we can handle it.

When the user clicks on the button we want to save the location to our database. So, onClicklistener will execute logic to push the value of latitude and longitude to our firebase database and show a toast message that will inform the user that it’s done.

onConnectionSuspended() : The connection to the google paly services may get lost, so, here be an attempt to reconnect to the google play services.

AndroidManifest.xml
We have to give permissions for ACCESS_FINE_LOCATION in our manifest file so that we can access user location.

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

    <uses-permission android:name="android.permission.ACCESS_FINE_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.gms.version"
            android:value="@integer/google_play_services_version" />
        <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>

Now, we can see our saved data in https://console.firebase.google.com  in the database section.

Here, we can see alert rules because we haven’t setup and authentication and security so anyone can read our database. Don’t forget to change authentication in the rules section. By default, only authenticated user can read or write data to our database.

If you are a beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

2 thoughts on “Display current location(latitude and longitude) in google map and save it to the Firebase database in Android

Leave a Reply

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