Working with user location

Jaromír Landa
Location-based services
2 min readOct 27, 2021

Very important part of working with user GPS location are permissions. We have created an utility for checking the permission..

class PermissionUtility {

companion object {

fun requestLocationPermission(context: FragmentActivity, requestCode: Int) {
requestPermissions(context, requestCode, Manifest.permission.ACCESS_FINE_LOCATION)
}

fun checkLocationPermission(context: FragmentActivity): Boolean
= checkPermissions(context, Manifest.permission.ACCESS_FINE_LOCATION)


private fun checkPermissions(context: FragmentActivity, permission: String): Boolean {
return ContextCompat.checkSelfPermission(
context,
permission
) == PackageManager.PERMISSION_GRANTED
}


private fun requestPermissions(context: FragmentActivity, requestCode: Int, permission: String) {
ActivityCompat.requestPermissions(
context,
arrayOf(permission),
requestCode
)

}
}

}

We have two universal methods for checking and requesting permissions and two of ours that check and request location permission.

More about permission here.

Next part was getting the location. We have also created a class for it. The class allows us to obtain current location or start/stop location updates (meaning getting the location periodically).

class LocationManager (private val activity: FragmentActivity) {

private var fusedLocationProviderClient: FusedLocationProviderClient

init {
fusedLocationProviderClient = FusedLocationProviderClient(activity)
}


@SuppressLint("MissingPermission")
fun getCurrentLocation(listener: OnSuccessListener<Location>) {
fusedLocationProviderClient.lastLocation
.addOnSuccessListener(listener)
}

@SuppressLint("MissingPermission")
fun startLocationUpdates(interval: Long, locationCallBack: LocationCallback) {
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.fastestInterval = interval
locationRequest.interval = interval

fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallBack,
Looper.getMainLooper()
)
}

fun stopLocationUpdates(locationCallBack: LocationCallback) {
fusedLocationProviderClient.removeLocationUpdates(locationCallBack)
}

}

And i code, we use the methods with the class with permissions.

binding.currentLocationFAB.setOnClickListener {
if (PermissionUtility.checkLocationPermission(requireActivity())){
addPointToCurrentLocation()
} else {
PermissionUtility.requestLocationPermission(requireActivity(), LOCATION_PERMISSION_REQUEST_CODE)
}
}

If we have permission, we can continue. If not, we need to request. In case we have location. We use the location manager.

private fun addPointToCurrentLocation(){
locationManager.getCurrentLocation(object : OnSuccessListener<Location>{
override fun onSuccess(p0: Location?) {
val action
= MapFragmentDirections.actionMapToAddPlace(p0!!.latitude.toFloat(),p0.longitude.toFloat())
findNavController().navigate(action)
}
})
}

--

--