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 deviceFollow 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
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
xmlns:android="http://schemas.android.com/apk/res/android"
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:
- Fetched the API key that we stored in Step 2.
- Initialized the Places API with the use of the API key.
- Initialized the Map fragment in the layout (activity_main.xml).
- Initialized fused location client.
- Initialized Button in the layout (activity_main.xml).
- Created a function to get the last location.
- Created a function to request a new location.
- Created a function for location callback.
- Created a function to check if the GPS of the device is turned on.
- Created a function to check if permissions for accessing the location are granted.
- Created a function to grant requests to permissions for accessing the location.
- 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.
Similar Reads
How to Implement Google's Places AutocompleteBar in Android?
If you ever used Google Maps on mobile or accessed from a desktop, you must have definitely typed in some location into the search bar and selected one of its results. The result might have had fields such as an address, phone numbers, ratings, timings, etc. Moreover, if you ever searched for a plac
5 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI fl
4 min read
How to Get Current Location Inside Android Fragment?
A Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
5 min read
How to Get Current Location in Android?
As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user's current location in Android. There are two ways to get the current location of
5 min read
How to Get Users Current Location on Google Maps in Flutter?
Nowadays Google Maps is one of the popular Applications for navigation or finding any Location. With this, we can find out the current Location of any person. So in this article, we are going to see how to get users' current Location in Flutter. Step By Step ImplementationStep 1: Create a New Projec
4 min read
How to Create Google Glass Options Menu in Android?
Google Glass is a wearable device developed by Google that allows users to perform various tasks such as taking photos, recording videos, and sending messages. In this article, we will show you how to create a Google Glass options menu in Android. Step By Step Implementation Step 1: To create a new
2 min read
How to Center a Button in a Linear Layout in Android?
LinearLayout is a view group that aligns all children vertically or horizontally in a single direction. The "android:orientation" parameter allows you to define the layout direction. A button is a component of the user interface that can be tapped or clicked to carry out an action. Nowadays while de
2 min read
How to Handle IME Options on Action Button Click in Android?
We often observe that a keyboard pops up when we try to enter input in editable fields. These inputs are generally accepted by the application for performing specific functions and display desired results. One of the most common editable fields, that we can see in most of the applications in daily u
3 min read
How to Create Google Lens Application in Android?
We have seen the new Google Lens application in which we can capture images of any product and from that image, we can get to see the search results of that product which we will display inside our application. What are we going to build in this article? We will be building a simple application in w
10 min read
How to Implement Country Code Picker in Android?
Country Code Picker (CCP) is an android library that helps users to select country codes (country phone codes) for telephonic forms. CCP provided a UI component that helps the user to select country codes, country flags, and many more in an android spinner. It gives well-designed looks to forms on t
3 min read