Search in sources :

Example 1 with GeocodingResult

use of com.example.placesdemo.model.GeocodingResult in project android-places-demos by googlemaps.

the class ProgrammaticAutocompleteToolbarActivity method geocodePlaceAndDisplay.

/**
 * Performs a Geocoding API request and displays the result in a dialog.
 *
 * @see https://developers.google.com/maps/documentation/geocoding/intro
 */
private void geocodePlaceAndDisplay(AutocompletePrediction placePrediction) {
    // Construct the request URL
    final String apiKey = BuildConfig.PLACES_API_KEY;
    final String url = "https://maps.googleapis.com/maps/api/geocode/json?place_id=%s&key=%s";
    final String requestURL = String.format(url, placePrediction.getPlaceId(), apiKey);
    // Use the HTTP request URL for Geocoding API to get geographic coordinates for the place
    JsonObjectRequest request = new JsonObjectRequest(Method.GET, requestURL, null, response -> {
        try {
            // Inspect the value of "results" and make sure it's not empty
            JSONArray results = response.getJSONArray("results");
            if (results.length() == 0) {
                Log.w(TAG, "No results from geocoding request.");
                return;
            }
            // Use Gson to convert the response JSON object to a POJO
            GeocodingResult result = gson.fromJson(results.getString(0), GeocodingResult.class);
            displayDialog(placePrediction, result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }, error -> Log.e(TAG, "Request failed"));
    // Add the request to the Request queue.
    queue.add(request);
}
Also used : GeocodingResult(com.example.placesdemo.model.GeocodingResult) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest)

Aggregations

JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)1 GeocodingResult (com.example.placesdemo.model.GeocodingResult)1 JSONArray (org.json.JSONArray)1 JSONException (org.json.JSONException)1