Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to Implement Current Location Button Feature in Google Maps in Android?

  • Last Updated : 23 May, 2021

The current location is a feature on Google Maps, that helps us locate the device’s position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going to implement this project using the Kotlin language. 

Screenshot of the actual Google Map App on Android device

Follow the below steps to implement a map and a button to navigate to the device’s current position

Step 1: Create a New Project in Android Studio

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2:  Get and hide the API key



Our application utilizes Google’s Places API to implement Google Map, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs. Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?.

Step 3: Adding the dependencies in the build.gradle file

We need to add the below dependency for importing libraries to support the implementation of the Google Map.

implementation ‘com.google.android.libraries.places:places:2.4.0’

Step 4: Adding permissions to the application in the Manifest.xml file

As the application majorly deals with the current location, we give the application the permissions to access the location. To give the application such permissions, declare permissions between the manifest and application opening tags in the following way.

XML




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

Step 5: Implementing a simple Button & Google Map fragment in the activity_main.xml file (front-end)



Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
  
    <fragment 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:id="@+id/map"
        tools:context=".MapsActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment" />
  
    <Button
        android:id="@+id/currentLoc"
        android:layout_width="30sp"
        android:layout_height="40sp"
        android:layout_alignBottom="@id/map"
        android:layout_alignEnd="@id/map"
        android:layout_alignRight="@id/map"
        android:layout_marginRight="30sp"
        android:layout_marginBottom="30sp"
        />
  
</RelativeLayout>

Step 6: Working with MainActivity.kt (back-end)

What we did in short is:

  1. Fetched the API key that we stored in Step 2.
  2. Initialized the Places API with the use of the API key.
  3. Initialized the Map fragment in the layout (activity_main.xml).
  4. Initialized fused location client.
  5. Initialized Button in the layout (activity_main.xml).
  6. Created a function to get the last location.
  7. Created a function to request a new location.
  8. Created a function for location callback.
  9. Created a function to check if the GPS of the device is turned on.
  10. Created a function to check if permissions for accessing the location are granted.
  11. Created a function to grant requests to permissions for accessing the location.
  12. Created a function to call getLastLocation() when permissions are granted.

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.*
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.libraries.places.api.Places
  
class MainActivity : AppCompatActivity(), OnMapReadyCallback {
  
    private val pERMISSION_ID = 42
    lateinit var mFusedLocationClient: FusedLocationProviderClient
    lateinit var mMap: GoogleMap
        
      // Current location is set to India, this will be of no use
    var currentLocation: LatLng = LatLng(20.5, 78.9)
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Fetching API_KEY which we wrapped
        val ai: ApplicationInfo = applicationContext.packageManager
            .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA)
        val value = ai.metaData["com.google.android.geo.API_KEY"]
        val apiKey = value.toString()
  
        // Initializing the Places API with the help of our API_KEY
        if (!Places.isInitialized()) {
            Places.initialize(applicationContext, apiKey)
        }
  
        // Initializing Map
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
  
        // Initializing fused location client
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
  
        // Adding functionality to the button
        val btn = findViewById<Button>(R.id.currentLoc)
        btn.setOnClickListener {
            getLastLocation()
        }
    }
  
    // Services such as getLastLocation()
      // will only run once map is ready
    override fun onMapReady(p0: GoogleMap) {
        mMap = p0
        getLastLocation()
    }
  
    // Get current location
    @SuppressLint("MissingPermission")
    private fun getLastLocation() {
        if (checkPermissions()) {
            if (isLocationEnabled()) {
  
                mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
                    val location: Location? = task.result
                    if (location == null) {
                        requestNewLocationData()
                    } else {
                        currentLocation = LatLng(location.latitude, location.longitude)
                        mMap.clear()
                        mMap.addMarker(MarkerOptions().position(currentLocation))
                        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16F))
                    }
                }
            } else {
                Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show()
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivity(intent)
            }
        } else {
            requestPermissions()
        }
    }
  
    // Get current location, if shifted
      // from previous location
    @SuppressLint("MissingPermission")
    private fun requestNewLocationData() {
        val mLocationRequest = LocationRequest()
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        mLocationRequest.interval = 0
        mLocationRequest.fastestInterval = 0
        mLocationRequest.numUpdates = 1
  
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        mFusedLocationClient.requestLocationUpdates(
            mLocationRequest, mLocationCallback,
            Looper.myLooper()
        )
    }
  
    // If current location could not be located, use last location
    private val mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            val mLastLocation: Location = locationResult.lastLocation
            currentLocation = LatLng(mLastLocation.latitude, mLastLocation.longitude)
        }
    }
  
    // function to check if GPS is on
    private fun isLocationEnabled(): Boolean {
        val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
            LocationManager.NETWORK_PROVIDER
        )
    }
  
    // Check if location permissions are
      // granted to the application
    private fun checkPermissions(): Boolean {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        ) {
            return true
        }
        return false
    }
  
    // Request permissions if not granted before
    private fun requestPermissions() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
            pERMISSION_ID
        )
    }
  
    // What must happen when permission is granted
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (requestCode == pERMISSION_ID) {
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                getLastLocation()
            }
        }
    }
}

Output:

Note: The application will prompt for permission requests, kindly allow once. Also, keep the device connected to the internet.




My Personal Notes arrow_drop_up
Recommended Articles
Page :