Example Code for Geocoding
package com.example.geocodingapp;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Geocoder usage to get coordinates from a location name
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
new Thread(() -> { // Run on background thread to avoid blocking UI
try {
List<Address> addresses = geocoder.getFromLocationName("Taj Mahal, Agra", 1);
if (addresses != null && !addresses.isEmpty()) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
Log.d("Geocoding", "Latitude: " + latitude + ", Longitude: " + longitude);
} else {
Log.d("Geocoding", "No address found");
}
} catch (IOException e) {
e.printStackTrace();
}
}).start(); // Must run network-related code in background thread
}
}
Expected Output: Latitude: 27.1751, Longitude: 78.0421
Code for Reverse Geocoding
package com.example.reversegeocodingapp;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
// Reverse geocoding should be run on a background thread
new Thread(() -> {
try {
// Coordinates for New York City (latitude, longitude)
List<Address> addresses = geocoder.getFromLocation(40.7128, -74.0060, 1);
if (addresses != null && !addresses.isEmpty()) {
String address = addresses.get(0).getAddressLine(0);
Log.d("Reverse Geocoding", "Address: " + address);
} else {
Log.d("Reverse Geocoding", "No address found");
}
} catch (IOException e) {
e.printStackTrace();
}
}).start(); // Start background thread
}
}
Expected Output: Address: New York, USA