Getting User Location In Android, The Jetpack Compose Way
Convert User’s Latitude and Longitude To Human Readable Format…
I was working on a project that required me to get the user’s location in a human-readable form and display it back to the user.
After going through a lot of Google search pages, I couldn’t find a code that worked perfectly for me, so I decided to write the code implementation myself and also derive inspiration from other legacy methods I found online.
After I have written and tested the code implementation that works well for me, I have broken it down into three different methods to make it easier to understand. Below, I’ll explain each method in details…
Fetching User Location…
The above code is simple and self-explanatory, but some parts need explanation, and I have numbered them.
- Inside the Location Callback Object, I gave two option to get the user location, each with their respective explanation
- 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
- Here, we call the onDispose method of DisposableEffect to stop requesting location when we are done.
- We return the requested Latitude and Longitude
Request Location Update
This is also self-explanatory, so we don’t have to waste any more time explaining it. What it does is create Location Request parameters to pass to the request. LocationUpdate of FusedLocationProviderClient
Stop Location Update…
This method stops all Location Update request to avoid unnecessary use of resources.
Conclusion…
With the three methods above we can easily request the user’s longitude and latitudes, but what if we want a human-readable location; This can be done by using the GeoLocation API provided by the Android Framework; Below is a simple way to archive that…
Full Code…
Below is the full code implementation
Thanks for hanging on. I hope you find this information helpful and educational. If there’s anything you’re curious about or if I missed anything important, please don’t hesitate to reach out and ask!
I’m here to help, and I promise to respond to every comment. Let’s keep the conversation going!
Until next time, I’m Jnr. Bye for now! 🖤