Geocoding and Reverse Geocoding Example in Android
1. Add Permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
2. Java Code for MainActivity.java
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView textView;
Geocoder geocoder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
geocoder = new Geocoder(this, Locale.getDefault());
// Geocoding: Get coordinates from address
Geocoding and Reverse Geocoding Example in Android
String locationName = "New York, USA";
try {
List<Address> addresses = geocoder.getFromLocationName(locationName, 1);
if (addresses != null && !addresses.isEmpty()) {
double lat = addresses.get(0).getLatitude();
double lon = addresses.get(0).getLongitude();
textView.setText("Geocoding:\nLat: " + lat + "\nLon: " + lon);
} catch (IOException e) {
e.printStackTrace();
// Reverse Geocoding: Get address from coordinates
double latitude = 40.7128;
double longitude = -74.0060;
try {
List<Address> revAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if (revAddresses != null && !revAddresses.isEmpty()) {
String address = revAddresses.get(0).getAddressLine(0);
textView.append("\n\nReverse Geocoding:\n" + address);
} catch (IOException e) {
e.printStackTrace();
3. Layout File (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
Geocoding and Reverse Geocoding Example in Android
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Notes
Use background threads for Geocoder operations.
Ensure internet access or offline map data is available.