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