how to implement google map in android studio store latitude and longitude on FireBase

 Google Sign in Firebase Android;

Google sign in Activity Code 


public class LoginActivity extends AppCompatActivity {


private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 1001;
GoogleSignInClient googleSignInClient;
private FirebaseAuth firebaseAuth;

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

SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
signInToGoogle();
}

});

configureGoogleClient();
}


private void configureGoogleClient() {

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_idd))
.requestEmail()
.build();

googleSignInClient = GoogleSignIn.getClient(this, gso);

SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);

firebaseAuth = FirebaseAuth.getInstance();
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
if (currentUser != null) {
Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());
//showToastMessage("Currently Logged in: " + currentUser.getEmail());
launchMainActivity(currentUser);
}
}
public void signInToGoogle() {
Intent signInIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
showToastMessage("Google Sign in Succeeded");
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Log.w(TAG, "Google sign in failed", e);
showToastMessage("Google Sign in Failed " + e);
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail());
showToastMessage("Firebase Authentication Succeeded ");
launchMainActivity(user);
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
showToastMessage("Firebase Authentication failed:" + task.getException());
}
}
});
}
private void showToastMessage(String message) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
}
private void launchMainActivity(FirebaseUser user) {
if (user != null) {
MapsActivity.startActivity(this, user.getDisplayName());
finish();
}
}
}
Google sign in Activity  Xml  Code 
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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=".LoginActivity">

<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

</com.google.android.gms.common.SignInButton>

</androidx.constraintlayout.widget.ConstraintLayout>
Google map Activity Xml Code:
<?xml version="1.0" encoding="utf-8"?>
<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=".MapsActivity" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textViewWelcome"
android:layout_width="match_parent"
android:textSize="18sp"
android:textColor="@color/black"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="welcome"
/>

<Button
android:id="@+id/buttonLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="logout"
android:textAllCaps="false"

/>
</LinearLayout>
</fragment>
Google Map Activity code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback ,
View.OnClickListener{

private static final int REQUEST_LOCATION_PERMISSION =1 ;
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
Marker marker;
private static final String TAG = "MainActivity";
private static final String ARG_NAME = "username";

public static void startActivity(Context context, String username) {
Intent intent = new Intent(context, MapsActivity.class);
intent.putExtra(ARG_NAME, username);
context.startActivity(intent);
}

FirebaseAuth firebaseAuth;
GoogleSignInClient googleSignInClient;
FirebaseDatabase firebaseDatabase;

DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
firebaseDatabase = FirebaseDatabase.getInstance();

databaseReference = firebaseDatabase.getReference(getIntent().getStringExtra(ARG_NAME));

TextView textView = findViewById(R.id.textViewWelcome);
if (getIntent().hasExtra(ARG_NAME)) {
textView.setText(String.format(getIntent().getStringExtra(ARG_NAME)));
}
findViewById(R.id.buttonLogout).setOnClickListener(this);

googleSignInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_SIGN_IN);
firebaseAuth = FirebaseAuth.getInstance();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}

locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();

Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
String locationnn = "Latitude : "+latitude+" , "+"Longitude : "+longitude;
String adress = addresses.get(0).getAddressLine(0);

String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(locationnn);

LatLng latLng = new LatLng(latitude, longitude);
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLng).title(adress));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20.0f));

} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
};


locationManager.requestLocationUpdates(LocationManager
.NETWORK_PROVIDER,0,0,locationListener);
locationManager
.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

}


@Override
protected void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}

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


@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonLogout:
signOut();
break;

}
}
private void signOut() {
firebaseAuth.signOut();
googleSignInClient.signOut().addOnCompleteListener(this,
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Signed out of google");

Intent intent = new Intent(MapsActivity.this,LoginActivity.class);
startActivity(intent);
finish();
}
});
}

}
Store google_maps_key on Android Manifest.Xml
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
put google map key on String.Xml
<string name="google_maps_key">AIzaSyDpYsfM3KzfxxoC2R9cjlJIClQz5lrfd0o</string>
Step-3: put uses-permission on manifest.Xml :
<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
tools:ignore="CoarseFineLocation" />
Step-3: put dependencies  on build.gradle :
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.android.gms:play-services-auth:20.1.0'
implementation 'com.google.firebase:firebase-database:20.0.3'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

Rajeshbhatt12

My name is Rajesh Bhatt. I am working as a senior android developer . I have created this blog for kotlin ,java and Android Development interview questions etc..

Previous Post Next Post