Geocode
Geocode
You need to add the necessary permissions in the [Link] file to access the internet
and use Google Maps services:
1. XML Code
<EditText
android:id="@+id/editTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_margin="16dp"/>
<Button
android:id="@+id/buttonGeocode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextAddress"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Geocode" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonGeocode"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:textSize="18sp"/>
</RelativeLayout>
2. Java Code-
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
editTextAddress = findViewById([Link]);
buttonGeocode = findViewById([Link]);
textViewResult = findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
String address = [Link]().toString();
new GeocodingTask().execute(address);
}
});
}
private class GeocodingTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String address = params[0];
String apiKey = "YOUR_API_KEY"; // Replace with your Google Maps
API key
String apiUrl =
"[Link] + address +
"&key=" + apiKey;
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection)
[Link]();
[Link]();
InputStream inputStream = [Link]();
Scanner scanner = new Scanner(inputStream);
StringBuilder stringBuilder = new StringBuilder();
while ([Link]()) {
[Link]([Link]());
}
return [Link]();
} catch (IOException e) {
[Link]();
return null;
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject location = [Link]("results")
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location");
double latitude = [Link]("lat");
double longitude = [Link]("lng");
[Link]("Latitude: " + latitude + "\nLongitude: " +
longitude);
} catch (JSONException e) {
[Link]();
}
} else {
[Link]("Error occurred while geocoding.");
}
}
}
}