I am implementing a function to find my latitude and longitude but it keeps giving a null value.
I declared android.permission.ACCESS_FINE_LOCATION, android.permission.ACCESS_BACKGROUND_LOCATION, android.permission.ACCESS_COARSE_LOCATION, and android.permission.INTERNET.
I granted all permissions and it shows a 'granted' toast but why my location is always null?
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var fusedLocationProviderClient : FusedLocationProviderClient
companion object {
private const val PERMISSION_REQUEST_ACCESS_LOCATION = 100
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
getCurrentLocation()
}
private fun getCurrentLocation() {
if( checkPermissions() )
{
if(isLocationEnabled())
{
if (ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
){
requestPermission()
return
}
fusedLocationProviderClient.lastLocation.addOnCompleteListener(this) { task ->
val location : Location? = task.result
if(location == null)
{
Toast.makeText(this, "Null Received", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(this, "Get Success", Toast.LENGTH_SHORT).show()
binding.txtLat.text = ""+location.latitude
binding.txtLong.text = ""+location.longitude
}
}
}
else
{
Toast.makeText(this, "Turn on location", Toast.LENGTH_SHORT).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
}
else
{
//request permission here
requestPermission()
}
}
private fun isLocationEnabled() : Boolean {
val locationManager : LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
private fun requestPermission() {
ActivityCompat.requestPermissions(
this, arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_ACCESS_LOCATION
)
}
private fun checkPermissions() : Boolean
{
if(ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
==PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
return true
}
return false
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == PERMISSION_REQUEST_ACCESS_LOCATION){
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(applicationContext, "Granted", Toast.LENGTH_SHORT).show()
getCurrentLocation()
}
else {
Toast.makeText(applicationContext, "Denied", Toast.LENGTH_SHORT).show()
}
}
}
}
As Google:
The getLastLocation() method returns a Task that you can use to get a Location object with the latitude and longitude coordinates of a geographic location. The location object may be null in the following situations:
Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted.
Solution:
1 Get last know location:
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
Log.d("last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
2 Receiving Location Updates:
To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates link
Here I shared how I solved the error for anyone having same problem that I got.
So the reason was there was no cache for the location that it could not access to my last location. I solved this problem by adding this.
add the below in if(location == null)
fusedLocationProviderClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() )
Then, I received an error to initialize locationCallback. So I added this.
2) add the below in onCreate
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
locationResult ?: return
for (location in locationResult.locations){
}
}
}
Related
So, im just trying to make a service that returns me the current location in android.
I've done all the work i think, but this is saying me that the system services are not available before onCreate()
Location Service :
class LocationService(context: Context): AppCompatActivity() {
companion object {
private const val PERMISSION_REQUEST_ACCESS_LOCATION = 100
}
private val context_activity: Context = context
private var fusedLocationProviderClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context_activity)
private var longitude: Double = 0.0
private var latitude: Double = 0.0
fun getLocation(): Array<Double> {
if (checkPermissions()) {
if (isLocationEnabled()) {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermission()
}
this.fusedLocationProviderClient.lastLocation.addOnCompleteListener(context_activity as Activity) { task ->
val location: Location? = task.result
if (location == null) {
Toast.makeText(context_activity, "Null received", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(
context_activity,
"Got Location Sucessfull",
Toast.LENGTH_SHORT
).show()
latitude = location.latitude
longitude = location.longitude
}
}
} else {
//settings open here
Toast.makeText(context_activity, "Turn on Location", Toast.LENGTH_SHORT).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
} else {
//request permission here
requestPermission()
}
return arrayOf(longitude, latitude)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == PERMISSION_REQUEST_ACCESS_LOCATION)
{
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(context_activity, "Granted", Toast.LENGTH_SHORT).show()
}else
{
Toast.makeText(context_activity, "Denied", Toast.LENGTH_SHORT).show()
}
}
}
private fun isLocationEnabled(): Boolean{
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
private fun checkPermissions(): Boolean {
return ActivityCompat.checkSelfPermission(context_activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context_activity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
private fun requestPermission(){
ActivityCompat.requestPermissions(context_activity as Activity, arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_ACCESS_LOCATION)
}
}
Main activity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//View Binding
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
var arrayD = arrayOf(LocationService(this).getLocation())
binding.tvLat.text = arrayD.get(0).toString()
binding.tvLong.text = arrayD.get(1).toString()
}
}
And please tell me , if there is any better way to get the location from the device.
I have an APP, and currently im getting some bad results, like my position beeing shown far away from where i am. Talking about KM's
The GoogleApiClient has been depreceted and now I am having some trouble learning the latest way to get constant location updates. Also, can I get the location updates using LocationCallback and LocationRequetMethod??
I am glad that I finally found it. The code is short. I have used LocationRequest and LocationCallback method. Also, I have used the fusedLocationProviderClient for requestLocationUpdates.
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationProviderClient;
TextView locationTextView;
LocationRequest locationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationTextView = findViewById(R.id.location_text);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//Not the best practices to get runtime permissions, but still here I ask permissions.
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(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
//Instantiating the Location request and setting the priority and the interval I need to update the location.
locationRequest = locationRequest.create();
locationRequest.setInterval(100);
locationRequest.setFastestInterval(50);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//instantiating the LocationCallBack
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
if (locationResult == null) {
return;
}
//Showing the latitude, longitude and accuracy on the home screen.
for (Location location : locationResult.getLocations()) {
locationTextView.setText(MessageFormat.format("Lat: {0} Long: {1} Accuracy: {2}", location.getLatitude(),
location.getLongitude(), location.getAccuracy()));
}
}
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
}
In activity_main.xml
<TextView
android:id="#+id/location_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/andika"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Also, before all these, I have added this in my dependencies
implementation 'com.google.android.gms:play-services-location:17.0.0'
And this in my Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And this keeps on updating in intervals you choose
Hi so continious location update is something you should avoid as it drains battery. You can use locationlistner where you could listen to location change. Say you want to update the location and get the attitude and longitude on every 10 meter change.
Sample code to check last,long every 100 meter
class LocationService : Service(), LocationListener {
protected var locationManager: LocationManager? = null
var checkGPS = false
var checkNetwork = false
// boolean canGetLocation = false;
var loc: Location? = null
// double latitude;
// double longitude;
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onLocationChanged(location: Location) {
// Toast.makeText(getApplicationContext(), Double.toString(location.getLatitude()) + location.getLongitude(), Toast.LENGTH_LONG).show();
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
override fun onCreate() {
super.onCreate()
location
}
Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
private val location: Location?
private get() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
)
!= PackageManager.PERMISSION_GRANTED
) {
}
locationManager = applicationContext
.getSystemService(LOCATION_SERVICE) as LocationManager
checkGPS = locationManager!!
.isProviderEnabled(LocationManager.GPS_PROVIDER)
checkNetwork = locationManager!!
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
locationManager!!.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this
)
if (locationManager != null) {
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
if (location != null) {
Toast.makeText(
applicationContext,
java.lang.Double.toString(location.latitude) + location.longitude + "from method",
Toast.LENGTH_LONG
).show()
}
}
}
Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
return loc
}
companion object {
private const val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 100
private const val MIN_TIME_BW_UPDATES: Long = 30
}
}
so I want to get the latitude and longitude from the device, but when I build my application on android Lollipop or API 22 I'm not getting the current latitude and longitude. is this because of android permission or what? here is my code
I'm using play service location version:
implementation 'com.google.android.gms:play-services-location:17.0.0'
LocationUser.kt
class LocationUser(context: Context) {
private var fusedLocation: FusedLocationProviderClient? = null
private val INTERVAL: Long = 300000
private val FASTEST_INTERVAL: Long = 300000
private val REQUEST_LOCATION_PERMISSION = 1
lateinit var locationRequest: LocationRequest
private lateinit var lastLocation: Location
fun startLocationUpdates(context: Context) {
Log.d("LOCATION UPDATE", "started location update")
locationRequest = LocationRequest()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = INTERVAL
locationRequest.fastestInterval = FASTEST_INTERVAL
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(locationRequest)
val locationSettingsRequest = builder.build()
val settingsClient = LocationServices.getSettingsClient(context)
settingsClient.checkLocationSettings(locationSettingsRequest)
fusedLocation = LocationServices.getFusedLocationProviderClient(context)
if (ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
return
}
fusedLocation!!.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
Log.d("LOCATION UPDATE", "end location update")
}
fun isPermissionGranted(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
) {
true
} else {
ActivityCompat.requestPermissions(
context as Activity, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
false
}
} else {
true
}
}
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
locationResult.lastLocation
onLocationChanged(context, locationResult.lastLocation)
super.onLocationResult(locationResult)
}
}
fun onLocationChanged(context: Context, location: Location) {
Log.d("UWUWU", "location changed")
lastLocation = location
val geocoder = Geocoder(context, Locale.getDefault())
val latitude = lastLocation.latitude
val longitude = lastLocation.longitude
val sharedPref = SharedPref(context)
Log.d("latitude", latitude.toString())
Log.d("longitude", longitude.toString())
sharedPref.saveStringPref("latitude_user", latitude.toString())
sharedPref.saveStringPref("longitude_user", longitude.toString())
try {
val addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 1)
val namaKota = addresses[0].subAdminArea
val namaKecamatan = addresses[0].locality
sharedPref.saveStringPref("alamat_user", "$namaKecamatan, $namaKota")
} catch (e: Exception) {
e.localizedMessage
}
Log.d("UWUWU", "location changed")
}
}
and in the activity I called the class like this
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val REQUEST_LOCATION_PERMISSION = 1
private val REQUESTING_LOCATION_UPDATES_KEY = "requesting_location_update"
private val requestingLocationUpdates = true
val locationUser = LocationUser(this)
#SuppressLint("SimpleDateFormat", "SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
../
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
checkUserGPS()
}
if(locationUser.isPermissionGranted(this)){
locationUser.startLocationUpdates(this)
}
Log.d("GRANTED ?", locationUser.isPermissionGranted(this).toString())
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_setting, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_settings) {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT).show()
}
}
}
private fun checkUserGPS() {
val dialog = AlertDialog.Builder(this)
dialog.setMessage("GPS tidak aktif, apakah kamu ingin megaktifkannya?")
.setCancelable(false)
.setPositiveButton("iya") { _, which ->
startActivityForResult(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 11)
}
.setNegativeButton("tidak") { dialog, _ ->
dialog.cancel()
finish()
}
.create()
.show()
}
override fun onResume() {
locationUser.startLocationUpdates(this)
super.onResume()
}
}
when I see log I noticed that the function of onLocationChange not called when function startLocationUpdates function is called. is this because of permission or what, I'm suffering StackOverflow and get this question which is vice versa with my problem, and I noticed the same thing which is locationcallback is not triggered
FusedLocationProviderClient requestLocationUpdates doesn't trigger LocationCallBack for API 23 above
I'm confused right now
The fused Location Provider will only maintain background location if at least one client is connected to it. Now just turning on the location service will not guarantee to store the last known location.
Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and getLastLocation() is invoked right away in onConnected(), that might not be enough time for the first location to arrive..
I suggest you to launch the Maps app first, so that there is at least some confirmed location, and then test your app.
I want to get the user location on button click. But it does not provide me location. I want to get user location by using android gps not with google play services
class NewPostActivity : AppCompatActivity(), LocationListener {
private val locationMangaer: LocationManager?
get() {
return getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
override fun onCreate(savedInstanceState: Bundle?) {
getLocationbtn.setOnClickListener {
locationMangaer!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10.toFloat(), this)
}
}
override fun onLocationChanged(location: Location?) {
Log.e("data", "called")
Log.e("data", "Location is ${location!!.latitude} and ${location.latitude}")
}
}
it is all of get current location code
class MainActivity : AppCompatActivity() {
val PERMISSION_ID = 42
lateinit var mFusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getLastLocation()
}
#SuppressLint("MissingPermission")
private fun getLastLocation() {
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
var location: Location? = task.result
if (location == null) {
requestNewLocationData()
} else {
findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
}
}
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
} else {
requestPermissions()
}
}
#SuppressLint("MissingPermission")
private fun requestNewLocationData() {
var 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()
)
}
private val mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
var mLastLocation: Location = locationResult.lastLocation
findViewById<TextView>(R.id.latTextView).text = mLastLocation.latitude.toString()
findViewById<TextView>(R.id.lonTextView).text = mLastLocation.longitude.toString()
}
}
private fun isLocationEnabled(): Boolean {
var locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
)
}
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
}
private fun requestPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_ID
)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == PERMISSION_ID) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
getLastLocation()
}
}
}
}
you have to add this to your ``` manifest.xml``
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
and this to your gradle
implementation 'com.google.android.gms:play-services-location:17.0.0'
I hope it will help you . happy code
i have a code like this
//onCreate()
btnmap.setOnClickListener{
viewMap()
}
//end of onCreate()
var MyLongitude:Double? = null
var Mylatitude:Double? = null
fun location(){
var locationListener = object : LocationListener {
override fun onLocationChanged(locationn: Location?) {
Mylongitude = locationn!!.longitude //i want to take this value
Mylatitude = locationn.latitude //i want to take this value
}
....
}
}
fun viewMap(){
Log.i(LOG, "$MyLongitude, $Mylatitude") //the output is null, null
val gmmIntentUri = Uri.parse("google.streetview:cbll=$MyLatitude,$MyLongitude")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent)
}
i wanna call a google map with intent to know where is my location now, to do that i need a value of latitude and longitude in location(), if you see my code when i call in Log MyLatitude and MyLongitude in viewMap() the output is always null even though it has been given a value in location() before
i've try to call viewMap() inside onLocationChanged() in location() and i get the value of latitude and longitude, but that is makes my app always call google map automatically every time the location changed
normally my app will call google map when i press the button btnmap
so, how to take a value of latitude and longitude from location() function for the intent in viewMap()?
You can learn more about user location from here. To get current location you have to ask user permission and define it in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
In your Activity's onCreate() method define the following:
val permissionState = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
if (permissionState != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), REQUEST_PERMISSIONS_REQUEST_CODE)
}
and override onRequestPermissionsResult function like here:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSIONS_REQUEST_CODE -> {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
getLocation()
}
}
}
So, that was the main part of getting user location. For the simplicity here is full code:
class MainActivity : AppCompatActivity() {
companion object {
private const val REQUEST_PERMISSIONS_REQUEST_CODE = 1
}
private lateinit var txtView: TextView
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var myLongitude: Double? = null
private var myLatitude: Double? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txtView = findViewById(R.id.txtView)
txtView.setOnClickListener {
viewMap()
}
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
val permissionState = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
if (permissionState != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), REQUEST_PERMISSIONS_REQUEST_CODE)
}
if (myLatitude == null || myLatitude == null)
getLocation()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSIONS_REQUEST_CODE -> {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
getLocation()
}
}
}
private fun viewMap() {
Log.i("LOG", "$myLongitude, $myLatitude")
val gmmIntentUri = Uri.parse("google.streetview:cbll=$myLatitude,$myLongitude")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent)
}
#SuppressLint("MissingPermission")
private fun getLocation() {
fusedLocationClient.lastLocation.addOnSuccessListener { location : Location? ->
location?.let {
myLongitude = it.longitude
myLatitude = it.latitude
}
}
}
}
For more detailed information about user location just refer to the link above, there are a lot of learning materials.