How to show current location on a google map on Android??

 Step 1 − Create a new project in Android Studio, go to File ⇒ New Project, and fill in all required details to create a new project.



Step 2 – Add the following dependency in the build.Gradle (Module: app)

implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'


Step 3 Open strings.xml and add the following code −

<resources>
   <string name="app_name">Sample</string>
   <string name="map_key" translatable="false">Enter your google API key here
</string>
</resources>

Step 4 − Add the following code to androidManifest.xml


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

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

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"


And


<meta-data

    android:name="com.google.android.geo.API_KEY"

    android:value="@string/map_key" />


Like This:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.INTERNET"/>
   <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:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/map_key"/>
      <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>

Step 5 – To Create Google Map_Key−

Map_Key


Step 6:- On the Dashboard Click On Enable Api And Services-



 



Step 7:- Open Map Sdk for Android



Step 8:- Enable Map Sdk

Step 9:- Back To Main Page And Open Credentials And Click ON Create Credentials 



Step 10:- Just Copy Paste Your Key In String File In Step-3 Map_Key

<resources>
   <string name="app_name">Sample</string>
   <string name="map_key" translatable="false">Enter your google API key here</string>
</resources>


Step 11:-Open activity_main.xml And Add Code This Code.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">


<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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=".MainActivity">


    <fragment

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/google_map"

        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>


Step 12:-Add Code In MainActivity


import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
   Location currentLocation;
   FusedLocationProviderClient fusedLocationProviderClient;
   private static final int REQUEST_CODE = 101
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
      fetchLocation();
   }
   private void fetchLocation() {
      if (ActivityCompat.checkSelfPermission(
         this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
         this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
         return;
      }
      Task<Location> task = fusedLocationProviderClient.getLastLocation();
      task.addOnSuccessListener(new OnSuccessListener<Location>() {
         @Override
         public void onSuccess(Location location) {
            if (location != null) {
               currentLocation = location;
               Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
               SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.myMap);
               assert supportMapFragment != null;
               supportMapFragment.getMapAsync(MainActivity.this);
            }
         }
      });
   }
   @Override
   public void onMapReady(GoogleMap googleMap) {
      LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
      MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Baba  here!");
      googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
      googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
      googleMap.addMarker(markerOptions);
   }
   @Override
   public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
      switch (requestCode) {
         case REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               fetchLocation();
         }
         break;
      }
   }
}


package com.c.googlemap;


import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;


import android.Manifest;

import android.content.pm.PackageManager;

import android.location.Location;

import android.os.Bundle;

import android.os.PowerManager;

import android.widget.Toast;


import com.google.android.gms.location.FusedLocationProviderClient;

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.tasks.OnSuccessListener;

import com.google.android.gms.tasks.Task;


public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {


    SupportMapFragment supportMapFragment;

    FusedLocationProviderClient fusedLocationProviderClient;

    private static final int REQUEST_CODE=101;


    Location currentLocation;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        getCurrentLocation();

    }


    private void getCurrentLocation() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

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

            return;

        }

        Task<Location> task = fusedLocationProviderClient.getLastLocation();

        task.addOnSuccessListener(new OnSuccessListener<Location>() {

            @Override

            public void onSuccess(Location location) {

                if(location!=null)

                currentLocation=location;

                Toast.makeText(getApplicationContext(), currentLocation.getLatitude()+""+currentLocation.getLongitude(),

                        Toast.LENGTH_SHORT).show();


                supportMapFragment = (SupportMapFragment) getSupportFragmentManager()

                        .findFragmentById(R.id.google_map);

                supportMapFragment.getMapAsync(MainActivity.this);


            }

        });

    }


    @Override

    public void onMapReady(GoogleMap googleMap) {

        LatLng latLng=new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());

        MarkerOptions options=new MarkerOptions().position(latLng).title("Hi Your Location");

        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,5));

        googleMap.addMarker(options);

    }

}


Step 13:- Just Run Your App And Tell Me Your Output In Comments Section.

Post a Comment

0 Comments