It is necessary to find Current Location Android Kotlin latitude longitude programmatically when you are developing location-based applications.
For example, when finding restaurants near by you, you need your current location, latitude and longitude.
In Current Location Android Kotlin example tutorial, you will learn to get current latitude and longitude of Android device.
We will use Google’s FusedLocationAPI for getting current location latitude longitude.
Following is the output of Current Location Android Kotlin example tutorial programmatically:
Download Source Code For Current Location Android Kotlin Example
[sociallocker]Download Kotlin_Current_GPS_Location[/sociallocker]
Step 1. New Project
Create a new project in Android Studio. Select your first activity as empty activity.
Step 2. Updating build.gradle(Module:app)
In build.gradle(Module:app) file add this:
compile 'com.google.android.gms:play-services:11.8.0'
Above lines will add necessary classes for integrating various google services like GPS, push notification, google map etc.
Step 3. Interfaces
Implement required interfaces
class MainActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Step 4. Required instances
Declare instances:
private var mLatitudeTextView: TextView? = null private var mLongitudeTextView: TextView? = null private var mGoogleApiClient: GoogleApiClient? = null private var mLocation: Location? = null private var mLocationManager: LocationManager? = null private var mLocationRequest: LocationRequest? = null private val listener: com.google.android.gms.location.LocationListener? = null private val UPDATE_INTERVAL = (2 * 1000).toLong() /* 10 secs */ private val FASTEST_INTERVAL: Long = 2000 /* 2 sec */ private var locationManager: LocationManager? = null
Step 5. Updating onCreate()
Put following in onCreate() function:
mLatitudeTextView = findViewById(R.id.latitude_textview) as TextView mLongitudeTextView = findViewById(R.id.longitude_textview) as TextView mGoogleApiClient = GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build() mLocationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager Log.d("gggg","uooo"); checkLocation() //check whether location service is enable or not in your phone
Step 6. Overriding methods
Override necessary methods.
@SuppressLint("MissingPermission") override fun onConnected(p0: Bundle?) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return } startLocationUpdates() mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) if (mLocation == null) { startLocationUpdates() } if (mLocation != null) { // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude())); //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude())); } else { Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show() } } override fun onConnectionSuspended(i: Int) { Log.i(TAG, "Connection Suspended") mGoogleApiClient!!.connect() } override fun onConnectionFailed(connectionResult: ConnectionResult) { Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode()) } override fun onStart() { super.onStart() if (mGoogleApiClient != null) { mGoogleApiClient!!.connect() } } override fun onStop() { super.onStop() if (mGoogleApiClient!!.isConnected()) { mGoogleApiClient!!.disconnect() } } override fun onLocationChanged(location: Location) { val msg = "Updated Location: " + java.lang.Double.toString(location.latitude) + "," + java.lang.Double.toString(location.longitude) mLatitudeTextView!!.text = location.latitude.toString() mLongitudeTextView!!.text = location.longitude.toString() Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() // You can now create a LatLng Object for use with maps val latLng = LatLng(location.latitude, location.longitude) }
Step 7. Adding permissions
Last but not least, put required permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
If you are targeting marshmallow and after versions (targetSdkVersion >=23) then you have to check for run-time permissions.
You can learn about this topic here at our separate example.
Now full source code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.parsaniahardik.kotlin_current_gps_location"> <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"> <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>
build.gradle(Module:app)
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 26 defaultConfig { applicationId "com.example.parsaniahardik.kotlin_current_gps_location" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } defaultConfig { multiDexEnabled true } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" //noinspection GradleCompatible implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' compile 'com.google.android.gms:play-services:11.8.0' }
Step 7. Full Source code for MainActivity.
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_marginTop="10dp" android:layout_marginLeft="10dp" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/latitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Latitude:" android:textSize="18sp" /> <TextView android:id="@+id/latitude_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/latitude" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/latitude" android:textSize="16sp" /> <TextView android:id="@+id/longitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Longitude:" android:layout_marginTop="24dp" android:textSize="18sp" /> <TextView android:id="@+id/longitude_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/longitude" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/longitude" android:textSize="16sp"/> </RelativeLayout>
MainActivity.kt
import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.location.Location import android.location.LocationManager import android.provider.Settings import android.support.v4.app.ActivityCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log 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.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.model.LatLng class MainActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener { private var mLatitudeTextView: TextView? = null private var mLongitudeTextView: TextView? = null private var mGoogleApiClient: GoogleApiClient? = null private var mLocation: Location? = null private var mLocationManager: LocationManager? = null private var mLocationRequest: LocationRequest? = null private val listener: com.google.android.gms.location.LocationListener? = null private val UPDATE_INTERVAL = (2 * 1000).toLong() /* 10 secs */ private val FASTEST_INTERVAL: Long = 2000 /* 2 sec */ private var locationManager: LocationManager? = null private val isLocationEnabled: Boolean get() { locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mLatitudeTextView = findViewById(R.id.latitude_textview) as TextView mLongitudeTextView = findViewById(R.id.longitude_textview) as TextView mGoogleApiClient = GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build() mLocationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager Log.d("gggg","uooo"); checkLocation() //check whether location service is enable or not in your phone } @SuppressLint("MissingPermission") override fun onConnected(p0: Bundle?) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return } startLocationUpdates() mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) if (mLocation == null) { startLocationUpdates() } if (mLocation != null) { // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude())); //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude())); } else { Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show() } } override fun onConnectionSuspended(i: Int) { Log.i(TAG, "Connection Suspended") mGoogleApiClient!!.connect() } override fun onConnectionFailed(connectionResult: ConnectionResult) { Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode()) } override fun onStart() { super.onStart() if (mGoogleApiClient != null) { mGoogleApiClient!!.connect() } } override fun onStop() { super.onStop() if (mGoogleApiClient!!.isConnected()) { mGoogleApiClient!!.disconnect() } } @SuppressLint("MissingPermission") protected fun startLocationUpdates() { // Create the location request mLocationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(UPDATE_INTERVAL) .setFastestInterval(FASTEST_INTERVAL) // Request location updates if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return } LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this) Log.d("reque", "--->>>>") } override fun onLocationChanged(location: Location) { val msg = "Updated Location: " + java.lang.Double.toString(location.latitude) + "," + java.lang.Double.toString(location.longitude) mLatitudeTextView!!.text = location.latitude.toString() mLongitudeTextView!!.text = location.longitude.toString() Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() // You can now create a LatLng Object for use with maps val latLng = LatLng(location.latitude, location.longitude) } private fun checkLocation(): Boolean { if (!isLocationEnabled) showAlert() return isLocationEnabled } private fun showAlert() { val dialog = AlertDialog.Builder(this) dialog.setTitle("Enable Location") .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + "use this app") .setPositiveButton("Location Settings") { paramDialogInterface, paramInt -> val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(myIntent) } .setNegativeButton("Cancel") { paramDialogInterface, paramInt -> } dialog.show() } companion object { private val TAG = "MainActivity" } }
In above class, there is a method
checkLocation() //check whether location service is enable or not in your phone
This method is used to check whether location service is on or off in your phone. If off, then it will pop up one dialog, which will take the user to settings to enable location service.
After following all the steps, you should be able get current location in terms of latitude and longitude with kotlin source code.
Java Version
Java Version of this tutorial is present at : Current GPS Location Android
Other dreamy tutorials
Cheers and keep healthy coding!