Blog Infos
Author
Published
Topics
Published

Convert User’s Latitude and Longitude To Human Readable Format…

 

Photo by henry perks on Unsplash

 

Fetching User Location…
/**
* Manages all location related tasks for the app.
*/
//A callback for receiving notifications from the FusedLocationProviderClient.
lateinit var locationCallback: LocationCallback
//The main entry point for interacting with the Fused Location Provider
lateinit var locationProvider: FusedLocationProviderClient
@SuppressLint("MissingPermission")
@Composable
fun getUserLocation(context: Context): LatandLong {
// The Fused Location Provider provides access to location APIs.
locationProvider = LocationServices.getFusedLocationProviderClient(context)
var currentUserLocation by remember { mutableStateOf(LatandLong()) }
DisposableEffect(key1 = locationProvider) {
locationCallback = object : LocationCallback() {
//1
override fun onLocationResult(result: LocationResult) {
/**
* Option 1
* This option returns the locations computed, ordered from oldest to newest.
* */
for (location in result.locations) {
// Update data class with location data
currentUserLocation = LatandLong(location.latitude, location.longitude)
Log.d(LOCATION_TAG, "${location.latitude},${location.longitude}")
}
/**
* Option 2
* This option returns the most recent historical location currently available.
* Will return null if no historical location is available
* */
locationProvider.lastLocation
.addOnSuccessListener { location ->
location?.let {
val lat = location.latitude
val long = location.longitude
// Update data class with location data
currentUserLocation = LatandLong(latitude = lat, longitude = long)
}
}
.addOnFailureListener {
Log.e("Location_error", "${it.message}")
}
}
}
//2
if (hasPermissions(
context,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
locationUpdate()
} else {
askPermissions(
context, REQUEST_LOCATION_PERMISSION, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
}
//3
onDispose {
stopLocationUpdate()
}
}
//4
return currentUserLocation
}
//data class to store the user Latitude and longitude
data class LatandLong(
val latitude: Double = 0.0,
val longitude: Double = 0.0
)
  1. Inside the Location Callback Object, I gave two option to get the user location, each with their respective explanation
  2. This part of the code check if our app has the required permissions; if the permission is available, request LocationUpdate(Code will be provided below) else ask for the permissions. Check out how to request multiple permission in jetpack compose here
  3. Here, we call the onDispose method of DisposableEffect to stop requesting location when we are done.
  4. We return the requested Latitude and Longitude
Request Location Update
@SuppressLint("MissingPermission")
fun locationUpdate() {
locationCallback.let {
//An encapsulation of various parameters for requesting
// location through FusedLocationProviderClient.
val locationRequest: LocationRequest =
LocationRequest.create().apply {
interval = TimeUnit.SECONDS.toMillis(60)
fastestInterval = TimeUnit.SECONDS.toMillis(30)
maxWaitTime = TimeUnit.MINUTES.toMillis(2)
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
//use FusedLocationProviderClient to request location update
locationProvider.requestLocationUpdates(
locationRequest,
it,
Looper.getMainLooper()
)
}
}
Stop Location Update…
fun stopLocationUpdate() {
try {
//Removes all location updates for the given callback.
val removeTask = locationProvider.removeLocationUpdates(locationCallback)
removeTask.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(LOCATION_TAG, "Location Callback removed.")
} else {
Log.d(LOCATION_TAG, "Failed to remove Location Callback.")
}
}
} catch (se: SecurityException) {
Log.e(LOCATION_TAG, "Failed to remove Location Callback.. $se")
}
}

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

Conclusion…
fun getReadableLocation(latitude: Double, longitude: Double, context: Context): String {
var addressText = ""
val geocoder = Geocoder(context, Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(latitude, longitude, 1)
if (addresses?.isNotEmpty() == true) {
val address = addresses[0]
addressText = "${address.getAddressLine(0)}, ${address.locality}"
// Use the addressText in your app
Log.d("geolocation", addressText)
}
} catch (e: IOException) {
Log.d("geolocation", e.message.toString())
}
return addressText
}
Full Code…
/**
* Manages all location related tasks for the app.
*/
//A callback for receiving notifications from the FusedLocationProviderClient.
lateinit var locationCallback: LocationCallback
//The main entry point for interacting with the Fused Location Provider
lateinit var locationProvider: FusedLocationProviderClient
@SuppressLint("MissingPermission")
@Composable
fun getUserLocation(context: Context): LatandLong {
// The Fused Location Provider provides access to location APIs.
locationProvider = LocationServices.getFusedLocationProviderClient(context)
var currentUserLocation by remember { mutableStateOf(LatandLong()) }
DisposableEffect(key1 = locationProvider) {
locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
/**
* Option 1
* This option returns the locations computed, ordered from oldest to newest.
* */
for (location in result.locations) {
// Update data class with location data
currentUserLocation = LatandLong(location.latitude, location.longitude)
Log.d(LOCATION_TAG, "${location.latitude},${location.longitude}")
}
/**
* Option 2
* This option returns the most recent historical location currently available.
* Will return null if no historical location is available
* */
locationProvider.lastLocation
.addOnSuccessListener { location ->
location?.let {
val lat = location.latitude
val long = location.longitude
// Update data class with location data
currentUserLocation = LatandLong(latitude = lat, longitude = long)
}
}
.addOnFailureListener {
Log.e("Location_error", "${it.message}")
}
}
}
if (hasPermissions(
context,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
locationUpdate()
} else {
askPermissions(
context, REQUEST_LOCATION_PERMISSION, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
}
onDispose {
stopLocationUpdate()
}
}
//
return currentUserLocation
}
fun stopLocationUpdate() {
try {
//Removes all location updates for the given callback.
val removeTask = locationProvider.removeLocationUpdates(locationCallback)
removeTask.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(LOCATION_TAG, "Location Callback removed.")
} else {
Log.d(LOCATION_TAG, "Failed to remove Location Callback.")
}
}
} catch (se: SecurityException) {
Log.e(LOCATION_TAG, "Failed to remove Location Callback.. $se")
}
}
@SuppressLint("MissingPermission")
fun locationUpdate() {
locationCallback.let {
//An encapsulation of various parameters for requesting
// location through FusedLocationProviderClient.
val locationRequest: LocationRequest =
LocationRequest.create().apply {
interval = TimeUnit.SECONDS.toMillis(60)
fastestInterval = TimeUnit.SECONDS.toMillis(30)
maxWaitTime = TimeUnit.MINUTES.toMillis(2)
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
//use FusedLocationProviderClient to request location update
locationProvider.requestLocationUpdates(
locationRequest,
it,
Looper.getMainLooper()
)
}
}
data class LatandLong(
val latitude: Double = 0.0,
val longitude: Double = 0.0
)
fun getReadableLocation(latitude: Double, longitude: Double, context: Context): String {
var addressText = ""
val geocoder = Geocoder(context, Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(latitude, longitude, 1)
if (addresses?.isNotEmpty() == true) {
val address = addresses[0]
addressText = "${address.getAddressLine(0)}, ${address.locality}"
// Use the addressText in your app
Log.d("geolocation", addressText)
}
} catch (e: IOException) {
Log.d("geolocation", e.message.toString())
}
return addressText
}

This article was previously published on proandroiddev.com

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
In the world of Jetpack Compose, where designing reusable and customizable UI components is…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu