Reverse Geocoding With Google Maps in Android
How to use the magical Geocoder class
How can we convert geographic coordinates to human-readable addresses? With the Android Geocoder API! Let’s dive in.
“Develop a passion for learning. If you do, you will never cease to grow.”
– Anthony J. D’Angelo
What Is Geocoder?
It is a class for handling geocoding and reverse geocoding.
- Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.
- Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.
What I’m going to use
- Android
Geocoder
class - Kotlin (programming language)
- View binding
- MVVM (Architectural pattern)
Overview
The amazing part here is I’m using the Geocoder
class with Google Maps. In many apps like Uber and Careem, you might have seen that when a user drags/moves on a map with a pin to select their location, the address changes on the top bar accordingly. This feature can be implemented using reverse geocoding.
Step 1
Make a project and add the Google Maps API key by following the documentation:
I am creating a simple layout with MapView
:
Step 2
Geocoder
has two methods:
getFromLocation
: Takes the latitude and longitude and gives an array of addresses known to the corresponding latitude and longitude.getFromLocationName
: Takes the address name as input (e.g. 1600 Amphitheatre Parkway) and provides an array of addresses known to correspond to that address.
I am using getFromLocation
, as I am converting latitude and longitude into a readable address:
I am getting location data using the LoadDataCallback
in the activity.
Step 3
Let’s see Geocoder
in action in the activity:
According to Google's docs, onCameraIdle()
is called “when the camera movement has ended, there are no pending animations, and the user has stopped interacting with the map.”
As I am using MVVM here, data is rendering through viewModel
. Here is a ViewModel
class:
Now run the app and you will see the magic!
Conclusion
I hope you have learned something new. Thanks for reading. Happy coding!
You can find the complete source code below:
Follow CodixLab for more tech knowledge.